Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Datagrid : On load, selection on current item (highlighting)

I have a WPF Datagrid binded to some properties in my ViewModel

<DataGrid AutoGenerateColumns="False" Name="dataGrid" SelectionMode="Single"
          ItemsSource="{Binding ItemList}" SelectedItem="{Binding SelectedItem}">
...
</DataGrid>

When my window load and the Datagrid too, I set the SelectedItem and it binds fine but the row isn't highlighted. The moment I click a row, the row highlight and the problem is resolved.

How can I set/trigger the highlighting of the SelectedItem in the DataGrid on load/initialization ?

EDIT:

It's actually selected because I have the little selection cell. It's just the rendering of the Highlighting that does not trigger.

enter image description here

like image 413
Philippe Lavoie Avatar asked Mar 04 '11 21:03

Philippe Lavoie


1 Answers

I had the same "problem" and finally found a pretty good solution to the problem. As you already said is not that the row isn't selected but that it does not highlight the row. If you watch carefully you will notice that when you click anywhere in the row (using the mouse) it still doesn't highlight the row, only the cells inside it.

So 2 options;

  • Create code to select the cells of the row
  • or create a Style.Trigger to highlight the row (which is the best option in my mind).

To do this, add something like this to the datagrid in the xaml-file:

            <DataGrid.RowStyle>
                <Style TargetType="DataGridRow">
                    <Style.Triggers>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter Property="Background" Value="DodgerBlue"/>
                            <Setter Property="Foreground" Value="White"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </DataGrid.RowStyle>

Hope it helps!

Cheers, LTB

like image 111
LTB Avatar answered Oct 04 '22 06:10

LTB