c# - WPF 将集合的集合绑定(bind)到 DataGrid

标签 c# .net wpf xaml

为了简化我的问题,假设我有一个属性,我将我的 DataGrid 绑定(bind)到:

public List<LibrarySection> Library { get; set; }

然后在我的每个 LibrarySection 中

class LibrarySection
{
   public string SectionName{ get; set; }
   public List<Book> Books { get; set; }
}

书看起来像这样:

class Book
{
   public string Name { get; set; }
   public string Author { get; set; }
   public string BookID { get; set; }
}

现在我如何绑定(bind)到属性库,以在 DataGrid 中实现所有书籍的列表: Book table

最佳答案

期望 LibrarySection 是 DataContext您的 DataGrid 您可以简单地添加 Books因为它是ItemsSource .

你如果AutoGenerateColumns设置为 true这已经显示了您的项目但是如果您想定义自己的列(更改标题和内容)您应该设置AutoGenerateColumns="false" .

然后您可以添加 Columns并告诉每个 Column绑定(bind)特定的 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 -属性(property)。 如果是这样,只需使用 ItemsSource="{Binding Library.Books}"

我还推荐使用 ObservableCollection<LibrarySection>ObservableCollection<Book>而不是 List<T>因为如果任何值发生变化,它会自动更新。

关于c# - WPF 将集合的集合绑定(bind)到 DataGrid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51629604/

相关文章:

C#如何在app.config文件中指定appData文件路径

C# 日期时间解析问题

c# - 使用 .NET 远程读取事件日志

c# - 为什么在此 MethodInfo 上找不到自定义属性

.net - 从 EventLogEntry.Category 获取类别文本

c# - Mvc 4.0 中的存储库模式

c# - 方法 'Open' 没有重载/'Run' 采用 '1' 参数

wpf - 遵循 MVVM 模式的自动完成文本框

c# - 如何在 wpf 中的内部 TextBoxView 上设置边距

c# - ObservableCollection 更新时如何更新 UI?