簡體   English   中英

將復雜數據綁定到ItemsControl

[英]Binding complex data to an ItemsControl

所以基本上我有一個對象列表,其中包含另一個對象列表。 可以說我有一個Class對象的列表。 班級包含Students名單。 每個學生都有一個簡單字符串形式的Name屬性。

因此,基本上我想要的是以下內容:用戶可以使用ComboBox選擇一個類。

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

這樣可行。

從組合框選擇一個項目后,用戶將看到該類別每個學生的名單(還記得屬性NameStudents

為此,我創建了一個簡單的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>

我的問題是:如何獲得標簽中的學生姓名?

您的視圖模型應該具有SelectedClass屬性,可以通過將其綁定到ComboBox的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接口,並在SelectedClass更改時觸發PropertyChanged事件。


在沒有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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM