The first row of MVVM Datagrid, selected by default, but not selected

I have a datagrid that is bound to a collection on my ViewModel. When the window loads, the datagrid fills up and the SelectedItem parameter is selected. (I know this because I have a detailed view associated with the selected item.) However, the line is not highlighted. If I click on a line, it will be highlighted and will work fine.

How to make a highlighted line highlighted when it is selected by default?

<DataGrid IsSynchronizedWithCurrentItem="True" SelectionUnit="FullRow" RowHeaderWidth="0" VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Visible" IsReadOnly="True" ItemsSource="{Binding Items}" SelectedItem="{Binding Path=SelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTextColumn Header="Run Date" Binding="{Binding Path=RunDate, StringFormat={}{0:MM-dd-yy HH:mm:ss} }" /> <DataGridTextColumn Header="Description" Binding="{Binding Description}" /> <DataGridTextColumn Header="Duration" Binding="{Binding Duration}" /> <DataGridTextColumn Header="Deviation" Binding="{Binding Deviation}" /> </DataGrid.Columns> </DataGrid> 
+7
c # wpf mvvm xaml datagrid
source share
1 answer

As mentioned in my comment, it is possible to focus the grid on a selection modified with behavior. So, you will get that selection will be highlighted:

 using System.Windows.Controls; using System.Windows.Interactivity; public class FocusGridOnSelectionChanged : Behavior<DataGrid> { protected override void OnAttached() { base.OnAttached(); AssociatedObject.SelectionChanged += AssociatedObject_SelectionChanged; } private void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e) { AssociatedObject?.Focus(); } protected override void OnDetaching() { AssociatedObject.SelectionChanged -= AssociatedObject_SelectionChanged; base.OnDetaching(); } } xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" <DataGrid ... > <i:Interaction.Behaviors> <yourbehaviorsns:FocusGridOnSelectionChanged/> </i:Interaction.Behaviors> ... </DataGrid> 

But I'm afraid that this is not the complete solution that you need, because if the grid loses focus, the selected elements will lose the selection.

So, if you want, this choice will also be highlighted after the grid loses focus, you must rewrite the DataGridRow control template, namely the visual style "UnfocusedSelected".

0
source share

All Articles