user3428422
user3428422

Reputation: 4570

WPF DataGrid, selected row color on DataGrid SelectedItem Change in MVVM

I have a WPF DataGrid that when I add a new item via a collection, I select that new item (row) using C# in the MVVM

// Adding the new item (which will create a new row)
ItemSourceCollection.Add(object);

// The itemSource would have refreshed, so now assign the SelectedItem of the grid
SelectedItem = ItemSourceCollection.Where(x => x.Id == Id).FirstOrDefault();

This works well as the row is selected. However, the row color doesn't match the color of when the user actually clicks on the row.

The xaml for the selected row color

<DataGrid.Resource>
    <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" 
               Color="#FF0000"/>
 </DataGrid.Resource>

So is it possible to use this color when a new row is added to the collection via code?

Upvotes: 2

Views: 2000

Answers (1)

dkozl
dkozl

Reputation: 33394

Problem is caused by the fact that there is a different brush for when selected item has focus and when it has not. So you either need to set focus or add this

<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="#FF0000"/>

to DataGrid.Resources. If you would be using .NET 4.5 there is dedicated brush for that and you would need to add

<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="#FF0000"/>

Upvotes: 3

Related Questions