[英]Binding complex data to an ItemsControl
So basically I have an list of an object that contains another List of objects. 所以基本上我有一个对象列表,其中包含另一个对象列表。 Lets say I have an List of the object
Class
. 可以说我有一个
Class
对象的列表。 And Class contains a list of Students
. 班级包含
Students
名单。 Every student has a property Name
as a simple string. 每个学生都有一个简单字符串形式的
Name
属性。
So basically what I want is the following: The user can select a class using a ComboBox. 因此,基本上我想要的是以下内容:用户可以使用ComboBox选择一个类。
<ComboBox ItemsSource="{Binding Path=Classes}" DisplayMemberPath="Name" />
That works. 这样可行。
After selecting an Item from that ComboBox, the user should see a list of every student in that class (remember the property Name
in Students
) 从组合框选择一个项目后,用户将看到该类别每个学生的名单(还记得属性
Name
中Students
)
I have created a simple ItemsControl for that purpose. 为此,我创建了一个简单的ItemsControl。
<ItemsControl ItemsSource="{Binding Classes}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Label Content="Name of the Student">
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
My question is: How do I get access to the students name in my label? 我的问题是:如何获得标签中的学生姓名?
Your view model should have a SelectedClass
property, which would be updated by binding it to the ComboBox's SelectedItem
property: 您的视图模型应该具有
SelectedClass
属性,可以通过将其绑定到ComboBox的SelectedItem
属性来进行更新:
<ComboBox ItemsSource="{Binding Classes}"
SelectedItem="{Binding SelectedClass}" .../>
You would then bind the ItemsControl to the Students
collection of the selected Class like this: 然后,您可以将ItemsControl绑定到所选班级的
Students
集合,如下所示:
<ItemsControl ItemsSource="{Binding SelectedClass.Students}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Note that the view model must implement the INotifyPropertyChanged interface and fire the PropertyChanged event when SelectedClass
changes. 请注意,视图模型必须实现INotifyPropertyChanged接口,并在
SelectedClass
更改时触发PropertyChanged事件。
In a quick and dirty approach without a SelectedClass view model property, you could also directly access the ComboBox's SelectedItem like this: 在没有SelectedClass视图模型属性的快速而肮脏的方法中,您还可以像这样直接访问ComboBox的SelectedItem:
<ComboBox x:Name="cbClasses" ItemsSource="{Binding Classes}" ... />
<ItemsControl ItemsSource="{Binding SelectedItem.Students, ElementName=cbClasses}">
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.