c# - WPF Binding a collection of collections to a DataGrid
问题描述
To simplify my problem, let's say that I have a property, that I am binding my DataGrid to:
public List<LibrarySection> Library { get; set; }
Then in each LibrarySection I have
class LibrarySection
{
public string SectionName{ get; set; }
public List<Book> Books { get; set; }
}
And book look like this:
class Book
{
public string Name { get; set; }
public string Author { get; set; }
public string BookID { get; set; }
}
Now how can I bind to property Library, to achieve in a DataGrid a list of all the books:
解决方案
期望 LibrarySection 是DataContext
您的 DataGrid 的,您可以简单地添加Books
它ItemsSource
。
如果AutoGenerateColumns
设置true
为此已经显示您的项目,但如果您想定义自己的列(更改标题和内容),您应该设置AutoGenerateColumns="false"
.
然后,您可以添加Columns
并告诉每个对象绑定您要绑定的集合中包含Column
的特定对象。Property
ItemsSource
<DataGrid ItemSource="{Binding Books}
AutoGenerateColumns="false"><!--should be false-->
<!-- Define custom columns -->
<DataGrid.Columns>
<DataGridTextColumn Binding="{Name}" Header="BookName" />
<DataGridTextColumn Binding="{Author}" Header="Book Author" />
<DataGridTextColumn Binding="{BookID}" Header="BookID" />
</DataGrid.Columns>
</DataGrid>
通常你应该有ViewModel
一个LibrarySection
- 属性。如果是这样,只需使用ItemsSource="{Binding Library.Books}"
我还建议使用ObservableCollection<LibrarySection>
andObservableCollection<Book>
而不是,List<T>
因为如果任何值发生变化,它会自动更新。
推荐阅读
- javascript - 为 Intl.NumberFormat 罗马尼亚列伊返回正确的货币
- c# - ASP.NET MVC:如何从控制器中找到视图?
- python - 如何使用 Python 3 引用某些列或行
- c++ - Swig,C++“包含嵌套太深”
- google-sheets - 带有 countif 的变量列导致公式解析错误
- python - 有没有办法在 Python 的 requests 模块中找到元素的确切路径?
- file - 包含 BlockRead() 的函数无法访问“结果”变量
- android - NavController 在方向更改时崩溃
- laravel - 显示连接的客户信息
- python - 乘以熊猫中的前导对角线值?