Reputation: 5087
Whenever the user clicks a button I want to get the selected row in a DataGrid and change its background color? I can get the index of the selected row using the SelectedIndex property but I do not know how to change the background of the same.
I use WPF, C# and .Net 4 in VS2010.
Thanks...
Upvotes: 2
Views: 5911
Reputation: 1
you can also use this:
<DataGrid ...>
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}},
Path=IsSelected}" Value="true">
<Setter Property="Background" Value="Transparent" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.CellStyle>
<!--...-->
Upvotes: 0
Reputation: 84647
It's better to use triggers for this sort of things but try the following
private void button_Click(object sender, RoutedEventArgs e)
{
DataGridRow dataGridRow = dataGrid.ItemContainerGenerator.ContainerFromIndex(dataGrid.SelectedIndex) as DataGridRow;
if (dataGridRow != null)
{
dataGridRow.Background = Brushes.Green;
}
}
Edit
The selected DataGridCells
will still override that background so you would probably have to handle that as well, using the Tag
property on the parent DataGridRow
for example
<DataGrid ...>
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}},
Path=Tag}" Value="ChangedBackground">
<Setter Property="Background" Value="Transparent" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.CellStyle>
<!--...-->
</DataGrid>
private void button_Click(object sender, RoutedEventArgs e)
{
DataGridRow dataGridRow = dataGrid.ItemContainerGenerator.ContainerFromIndex(dataGrid.SelectedIndex) as DataGridRow;
if (dataGridRow != null)
{
dataGridRow.Background = Brushes.Green;
dataGridRow.Tag = "ChangedBackground";
}
}
Upvotes: 3
Reputation: 30097
Try this
//get DataGridRow
DataGridRow row = (DataGridRow)dGrid.ItemContainerGenerator.ContainerFromIndex(RowIndex);
row.Background = Brushes.Red;
Upvotes: 2