我有一个DataGrid
并且我希望选定的行和聚焦的行同步,即如果聚焦的行发生变化,那么选定的行也会发生变化,如果选定的行发生变化,它就会成为聚焦的行。
给定具有以下 XAML 的 WPF 窗口,如何同步焦点行和选定行?
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.Resources>
<x:Array x:Key="MyList" Type="sys:String" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib">
<sys:String>Hello</sys:String>
<sys:String>World</sys:String>
<sys:String>World</sys:String>
<sys:String>World</sys:String>
<sys:String>World</sys:String>
<sys:String>World</sys:String>
<sys:String>World</sys:String>
<sys:String>World</sys:String>
<sys:String>World</sys:String>
</x:Array>
<Style TargetType="{x:Type DataGrid}">
<Setter Property="AlternationCount" Value="2" />
<Setter Property="AutoGenerateColumns" Value="False"/>
</Style>
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Focusable" Value="False"/>
</Style>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="Focusable" Value="True"/>
<Style.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="AlternationIndex" Value="0"/>
<Condition Property="IsSelected" Value="False"/>
</MultiTrigger.Conditions>
<Setter Property="Background" Value="White"/>
</MultiTrigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="AlternationIndex" Value="1"/>
<Condition Property="IsSelected" Value="False"/>
</MultiTrigger.Conditions>
<Setter Property="Background" Value="Gainsboro"/>
</MultiTrigger>
<Trigger Property="AlternationIndex" Value="1">
<Setter Property="Background" Value="Gainsboro"/>
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="#BF228B22"/>
<Setter Property="BorderBrush" Value="ForestGreen"/>
<Setter Property="BorderThickness" Value="1"/>
</Trigger>
</Style.Triggers>
</Style>
</Grid.Resources>
<DataGrid ItemsSource="{StaticResource MyList}">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding}" Width="*"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
通过下图,您可以看到红色的焦点矩形和绿色的选定行显然不同步,因为我相信这是默认行为。我想要的是让他们始终保持一致,即 SelectedRow 始终是 Focused,而 FocusedRow 始终是 Selected。