【问题标题】:WPF DataGrid style cells based on index基于索引的 WPF DataGrid 样式单元格
【发布时间】:2012-10-11 10:47:19
【问题描述】:

我将 DataTable 绑定到 WPF DataGrid(DataGrid 上自动生成的列)。

我想为第一列、最后一列和最后一行中的所有单元格指定不同的样式。

如何做到这一点?

编辑

这里的问题是我没有定义属性名称的数据对象,并且 DataTable 列名称不是恒定的,因为它是动态的,具有自动生成的列。

AutoGeneratingColumn 事件 - e.DisplayIndex 始终为 -1,是否有从此处到 DataTable 的列和行索引的路径?

转换器 - 如何传入单元格的行和列索引?

【问题讨论】:

标签: c# wpf xaml datagrid wpfdatagrid


【解决方案1】:

假设您将单元格样式和行样式存储在 XAML 资源中的某个位置,我建议您在代码隐藏中处理数据网格的两个事件,它们是:

int c = myDataTable.Rows.Count;
myDataGrid.AutoGeneratedColumns += (s, e) =>
{
   myDataGrid.Columns[myDataGrid.Columns.Count - 1].CellStyle = this.Resources["myCellStyle"] as Style;
   myDataGrid.Columns[0].CellStyle = this.Resources["myCellStyle"] as Style;
};
myDataGrid.LoadingRow += (s, e) =>
{
   int x = e.Row.GetIndex();
   if (c - 1 == x) e.Row.Style = this.Resources["myRowStyle"] as Style;
};

HTH

【讨论】:

  • 谢谢米歇尔 - 有时最好/唯一的方法是代码中的一些后列/行循环:)
  • 是的,可能有更好的解决方案,但有时我更喜欢更快的方式来完成任务!
猜你喜欢
  • 2017-07-22
  • 2020-03-27
  • 2023-01-13
  • 1970-01-01
  • 2011-05-12
  • 1970-01-01
  • 1970-01-01
  • 2016-04-28
  • 1970-01-01
相关资源
最近更新 更多