如何将嵌套的可观察集合值绑定到ListView

时间:2018-06-27 06:45:36

标签: listview uwp observablecollection

我想在列表视图中显示所有学生姓名。我的操作如下所示,但是它显示的列表视图为空。

 public  class ClassRoomDetailsList
{
    public int ClassRoomID { get; set; }
    public ObservableCollection<StudentsList> StudentsArray { get; set; }
}

public class StudentsList
{
    public string StudentName{ get; set; }

}


public static ObservableCollection<ClassRoomDetailsList> _ClassRoomDetailsList = new ObservableCollection<ClassRoomDetailsList>();
//assigned values to observable collection here
list1.ItemsSource = AppGlobals._ClassRoomDetailsList;

 <ListView x:Name="list1" HorizontalAlignment="Right"  Height="500" Width="500"  Background="Violet" >
           <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Vertical">
                     <Border Background="#b9fbc9" VerticalAlignment="Center">
                     <TextBlock Text="{Binding  StudentName}" FontSize="30" HorizontalAlignment="Center" VerticalAlignment="Center"    Foreground="Black"/>
                     </Border>
                     </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

我已检查_ClassRoomDetailsList正确包含学生姓名。是的。那么空列表视图的问题是什么?

1 个答案:

答案 0 :(得分:0)

_ClassRoomDetailsList是一个ObservableCollection<ClassRoomDetailsList>对象,其子项是ClassRoomDetailsList对象,但是您的ListView希望绑定StudentsList对象的StudentName,因此您的{ {1}}应该是ListView.ItemsSource对象。

您在ListView的DataTemplate中的绑定应绑定ObservableCollection << strong> T >中的 T 类对象的属性。这是一个基于您的模型的简单示例。

ObservableCollection<StudentsList>

有关在uwp应用程序中进行绑定的更多详细信息,请参阅主题Data binding overview