代码之家  ›  专栏  ›  技术社区  ›  user2877820

将复杂数据绑定到ItemsControl

  •  0
  • user2877820  · 技术社区  · 7 年前

    基本上我有一个对象列表,其中包含另一个对象列表。假设我有一个对象列表 Class Students . 每个学生都有自己的财产 Name 作为简单字符串。

    基本上我想要的是: 用户可以使用组合框选择类。

    <ComboBox ItemsSource="{Binding Path=Classes}" DisplayMemberPath="Name" />
    

    这是可行的。

    从该组合框中选择一个项目后,用户应该会看到该类中每个学生的列表(记住属性 名称 在里面 学生 )

    我为此创建了一个简单的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>
    

    1 回复  |  直到 7 年前
        1
  •  1
  •   Clemens    7 年前

    您的视图模型应该具有 SelectedClass SelectedItem 属性:

    <ComboBox ItemsSource="{Binding Classes}"
              SelectedItem="{Binding SelectedClass}" .../>
    

    然后将ItemsControl绑定到 Students 所选类的集合如下:

    <ItemsControl ItemsSource="{Binding SelectedClass.Students}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
    

    注意,视图模型必须实现INotifyPropertyChanged接口,并在以下情况下激发PropertyChanged事件: 变化。


    在没有SelectedClass视图模型属性的快速脏方法中,您还可以直接访问组合框的SelectedItem,如下所示:

    <ComboBox x:Name="cbClasses" ItemsSource="{Binding Classes}" ... />
    
    <ItemsControl ItemsSource="{Binding SelectedItem.Students, ElementName=cbClasses}">
    ...