简体   繁体   中英

Get selected Row in DataGrid and Change the background color

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...

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";
    }
}

Try this

//get DataGridRow
DataGridRow row = (DataGridRow)dGrid.ItemContainerGenerator.ContainerFromIndex(RowIndex);
row.Background = Brushes.Red;

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>
<!--...-->

DataGridRow has Background property. Is it what you need?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM