ToB企服应用市场:ToB评测及商务社交产业平台

标题: Wpf DataGrid设置列标题动态绑定实例 [打印本页]

作者: 瑞星    时间: 2023-10-27 03:54
标题: Wpf DataGrid设置列标题动态绑定实例
在 WPF 中,可以使用 DataGrid 控件来显示和编辑表格式的数据。要设置 DataGrid 列标题的动态绑定,可以使用 DataGrid 的列定义和绑定功能。
以下是一个示例,展示如何使用动态绑定设置 DataGrid 的列标题:
  1. <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding PersonsView}">
  2.                 <DataGrid.Columns>
  3.                     <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
  4.                     <DataGridTextColumn Header="Age" Binding="{Binding Age}"/>
  5.                     
  6.                     <DataGridTextColumn Width="120" Binding="{Binding Email}">
  7.                         
  8.                         <DataGridTextColumn.Header>
  9.                            
  10.                             <TextBlock Text ="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window},Path=DataContext.HeaderEmail,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" />
  11.                         </DataGridTextColumn.Header>
  12.                     </DataGridTextColumn>
  13.                 </DataGrid.Columns>
  14.             </DataGrid>
复制代码
  1. public class DataGridViewModel : INotifyPropertyChanged
  2.     {
  3.         public ObservableCollection<Person> Persons { get; set; } = new ObservableCollection<Person>()
  4.         {
  5.             new Person() { Name = "John Doe", Age = 25, Email = "john@example.com" },
  6.             new Person() { Name = "Jane Smith", Age = 30, Email = "jane@example.com" },
  7.             // Add more items here...
  8.         };
  9.         public DataGridViewModel()
  10.         {
  11.             this.PersonsView = new CollectionViewSource { Source = this.Persons };
  12.             this.DataContext = this;
  13.             HeaderEmail = "Email";
  14.         }
  15.         public ICollectionView PersonsView { get; set; }
  16.         public event PropertyChangedEventHandler PropertyChanged;
  17.         private string headerEmail;
  18.         public string HeaderEmail
  19.         {
  20.             get { return headerEmail; }
  21.             set
  22.             {
  23.                 headerEmail = value;
  24.                 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(HeaderEmail)));
  25.             }
  26.         }
  27.     }
复制代码
  这样,DataGrid 的列标题将会根据定义的数据源动态显示。在示例中,通过将 DataGrid 的 ItemsSource 属性绑定到 ViewModel 中的 ObservableCollection,并通过列定义中的 Header 和 Binding 属性来指定列标题和数据源中的字段。
  

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4