Reputation: 50
I'm facing issues when trying to change a DataGrid
row in the code behind of a WPF
app. My objective is to change the row color when the row is selected and when a button Valider
is clicked. 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
. The debugger point to the dataGridRow to be null (the row contains data though).
Upvotes: 2
Views: 2926
Reputation: 169150
The SelectedItem
property refers to the corresponding object in the Items
collection. You could use the ItemContainerGenerator
to get a reference to the DataGridRow
container:
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.
Upvotes: 4