2
votes

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?

1
Has DataGrid got focus? Did you try myDataGrid.Focus()? - dkozl
The code above is in the VIewModel so I won't be able to get to the DataGrid control itself. However, I don't mind going to the View so I will have a look from that prospective - user3428422
You can set focus in the view but there is different color for selected item when it's focused and when it's not - dkozl
Oh right, I didn't know, cheers, so how do I set the color of the SelectedItem then? cheers! - user3428422
Are you using .NET 4.5? - dkozl

1 Answers

2
votes

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"/>