将标签值设置为绑定到列表框的给定对象的 属性 的标签值

Set label value to that of a property of a given object that is bound to a listbox

所以我有一个 ListBox 通过...

绑定到学生对象列表
listBox_studentListBox.ItemsSource = studentList;

我有一个按钮可以将数据保存到列表中。

private void btn_studentListBox_Add_Click(object sender, RoutedEventArgs e)
{
      currentID = getStudentID();//getStudentID() just finds an available student ID, used to recycle ids of deleted student
      studentList.Add(new cls_student() { studentName = txtBox_studentInfoName.Text, studentID = currentID });
      listBox_studentListBox.DisplayMemberPath = "studentName";
      listBox_studentListBox.SelectedValue = "studentID";
      listBox_studentListBox.Items.Refresh();
}

现在,当我单击 ListBox 中的给定项目时,我想加载它的数据。我正在努力做到这一点。

private void listBox_studentListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
     //Load data into labels
}

我的学生对象在这里

public class cls_student
{
    public string studentName { get; set; }
    public int studentID { get; set; }

    public List<cls_assignment> assignmentList = new List<cls_assignment>();
}

如您所见,我在学生对象中存储了另一个列表,但我们稍后会担心将该列表加载到不同的 ListBox

我关心的是如何根据我的 selection 访问特定的学生对象(只需物理左键单击 ListBox 中调用 SelectionChanged 事件处理程序的对象)以能够在标签中为用户显示该数据。

我了解到,通过在我的添加事件处理程序中设置 DisplayMemberPath,我可以选择 ListBox 将每个绑定的学生对象显示为什么。问题是我不知道如何将某种值绑定到 ListBox 中的那个对象。我的想法是,如果我可以将一个值绑定到该对象,那么当我 select 它然后将其数据加载到标签中时,我就可以访问我想要的确切学生对象。

感谢所有反馈 - 这是最近 post 的更新 post,由于我将对象添加到 ListBox 的 .Items 属性 而被要求删除而不是将其与 ItemsSource.

绑定

编辑: 感谢回复,我看到如果我这样做 SelectedItem 我可以到达该对象。我现在有了这个代码。

private void listBox_studentListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
      testlabel.Content = "SelectedIndex: " + listBox_studentListBox.SelectedIndex;
      cls_student selectedStudent = (cls_student)listBox_studentListBox.SelectedItem;
      lbl_studentInfoName.Content = selectedStudent.studentName;
}

我的问题是 selectedStudent 的作用域是仅在事件处理程序期间还是持续到事件处理程序之后?对于上下文,我习惯了 C++,在那里我必须删除所有内容,否则我会发生内存泄漏。我是 C# 新手。

在您的视图模型上放置一个学生 属性。当它改变时提高 PropertyChanged。

将列表框的 SelectedItem 绑定到 Student 属性。

你应该使用 Binding:

<ListBox Name="listBox_studentListBox">
     <ListBox.ItemTemplate>
         <DataTemplate>
             <WrapPanel>
                 <TextBlock Text="{Binding studentName}" />
             </WrapPanel>
         </DataTemplate>
     </ListBox.ItemTemplate>
</ListBox>

对于Label

<Label Content="{Binding ElementName=listBox_studentListBox, Path=SelectedItem.studentID}" />

后面的代码中:

currentID = getStudentID();
studentList.Add(new cls_student() { studentName = txtBox_studentInfoName.Text, studentID = currentID });
listBox_studentListBox.ItemsSource = studentList;