简体   繁体   中英

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?

You're defining a style but don't do anything in this style. You have to define some Setter s 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>

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM