[英]Changing a WPF Datagrid Row background color programmatically
I'm facing issues when trying to change a DataGrid
row in the code behind of a WPF
app. 尝试在
WPF
应用程序后面的代码中更改DataGrid
行时遇到问题。 My objective is to change the row color when the row is selected and when a button Valider
is clicked. 我的目标是在选择行并单击按钮
Valider
器时更改行颜色。 My code is shown below. 我的代码如下所示。 I found some answers but none of them where useful for my case.
我找到了一些答案,但没有一个对我的情况有用。
private void Valider_Click(object sender, RoutedEventArgs e)
{
DataGridRow dataGridRow = InventaireItemGrid.SelectedItem as DataGridRow;
dataGridRow.Background = Brushes.Green;
}
When I execute, I get a NullReferenceException
. 当我执行时,我得到一个
NullReferenceException
。 The debugger point to the dataGridRow to be null (the row contains data though). 调试器将dataGridRow指向null(尽管该行包含数据)。
The SelectedItem
property refers to the corresponding object in the Items
collection. SelectedItem
属性引用Items
集合中的相应对象。 You could use the ItemContainerGenerator
to get a reference to the DataGridRow
container: 您可以使用
ItemContainerGenerator
获取对DataGridRow
容器的引用:
private void Valider_Click(object sender, RoutedEventArgs e)
{
DataGridRow dataGridRow = InventaireItemGrid.ItemContainerGenerator.ContainerFromItem(InventaireItemGrid.SelectedItem) as DataGridRow;
if (dataGridRow != null)
dataGridRow.Background = Brushes.Green;
}
There are most probably better ways of doing whatever you are trying to do though, for example using data binding and triggers. 尽管有很多更好的方法可以做您想做的事情,例如使用数据绑定和触发器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.