user4393725
user4393725

Reputation:

Does not change color selected row in Datagrid

I want to load window in Datagrid 5 row selected

My code, but color does not change

DataGridRow row = (DataGridRow)DataGridService.ItemContainerGenerator.ContainerFromIndex(5);
                object item = DataGridService.Items[5];
                DataGridService.SelectedItem = item;

                DataGridService.ScrollIntoView(item);
                row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

Xaml

<DataGrid.Resources>
   <SolidColorBrush x:Key="SelectionColorKey" Color="Red"/>
      <Style TargetType="DataGridRow">
          <Style.Resources>
             <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="{Binding Source={StaticResource SelectionColorKey}, Path=Color}"/>
          </Style.Resources>
      </Style>
</DataGrid.Resources>

May be i not correct formulated problem. I need on load window, background row 5 was red color and focus was in 5 row

It does not work

 DataGridService.SelectedItem = DataGridService.Items[5];

strangely in Winforms this makes easy

How selected first row?

Why is the problem with selected color?

Upvotes: 1

Views: 1505

Answers (2)

user4393725
user4393725

Reputation:

I found the solution, it is necessary to set the focus on Datagrid

DataGridService.Focus();
            DataGridRow row = (DataGridRow)DataGridService.ItemContainerGenerator.ContainerFromIndex(100);
            object item = DataGridService.Items[100];
            DataGridService.SelectedItem = item;


            DataGridService.ScrollIntoView(item);
            row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

Upvotes: 1

dymanoid
dymanoid

Reputation: 15197

You're defining a style but don't do anything in this style. You have to define some Setters to set properties of the styled object.

Something like this:

<DataGrid.Resources>
    <Style TargetType="DataGridRow">
        <Style.Triggers>
            <Trigger Property="IsSelected" Value="True">
                <Setter Property="Background" Value="Red"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</DataGrid.Resources>

Upvotes: 1

Related Questions