WPF:如何在运行时更改数据网格单元格的背景颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13044500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF: How to change the background color of a datagrid cell on runtime
提问by Diego
I am displaying two datatables (let's call them left and right) in two datagrids and it works. However what I want to do is to allows users compare two rows (left and right) based on the selection and change the background when the cells are different.
我在两个数据网格中显示两个数据表(让我们称它们为左右)并且它可以工作。但是我想要做的是允许用户根据选择比较两行(左和右)并在单元格不同时更改背景。
Sample:
样本:
Left
|A|B|C|
|1|2|3|
|1|2|3|
|1|2|3|
左
|A|B|C|
|1|2|3|
|1|2|3|
|1|2|3|
Right
|A|B|C|
|1|2|4|
|1|2|3|
|1|2|3|
右
|A|B|C|
|1|2|4|
|1|2|3|
|1|2|3|
In XAML my Datagrids look like:<DataGrid Grid.Column="0" x:Name="leftData" HorizontalAlignment="Stretch" >
</DataGrid>
在 XAML 中,我的 Datagrids 看起来像:<DataGrid Grid.Column="0" x:Name="leftData" HorizontalAlignment="Stretch" >
</DataGrid>
And in Code I am binding the datagrid to the DataTable:
在代码中,我将数据网格绑定到数据表:
TableRows = new DataTable();
leftData.ItemsSource = TableRows;
When the user selects the first row on the left and right, the cells on column C should be marked with a red background.
当用户选择左右第一行时,C列的单元格应该用红色背景标记。
How is the better approach for doing that in WPF? Is it possible to do that with DataGrid in WPF?
在 WPF 中这样做的更好方法是什么?是否可以使用 WPF 中的 DataGrid 做到这一点?
采纳答案by Diego
Finally I found the solution. The DataGrid control does not offer a way to get a DataGridCell, however it is possible to get it from the DataGrid control by using the VisualTreeHelper in order to get the DataGridCellsPresenter and from the presenter it is possible to get the DataGridCell.
最后我找到了解决方案。DataGrid 控件不提供获取 DataGridCell 的方法,但是可以通过使用 VisualTreeHelper 从 DataGrid 控件获取它以获取 DataGridCellsPresenter,并且可以从 Presenter 获取 DataGridCell。
More information and the code can be found here:
更多信息和代码可以在这里找到:
http://techiethings.blogspot.ch/2010/05/get-wpf-datagrid-row-and-cell.html
http://techiethings.blogspot.ch/2010/05/get-wpf-datagrid-row-and-cell.html
回答by Steoates
you could do something like
你可以做类似的事情
//dataControl would be the name of your control in the XAML
var cell = dataControl.Cells[columnIndex,rowIndex];
cell.Background = new SolidBrush(Colours.Red);
obviously you would need to implement this inside any logic you currently have, if you post more could then I would have a better idea of where its going
显然你需要在你目前拥有的任何逻辑中实现它,如果你发布更多,那么我会更好地了解它的去向

