我有一个datagrid绑定到我的viewmodel上的集合.当窗口加载时,填充数据网格并设置SelectedItem. (我知道这是因为我有一个绑定到所选项目的详细视图.)但是该行未突出显示.如果我点击该行,它将突出显示并正常工作.
当默认选择时,如何使所选行突出显示?
<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>
解决方法
正如我的评论中所提到的,有可能将网格集中在通过行为改变的选择上.所以你会得到,选择将突出显示:
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>
但我担心,这不是你所追求的完整解决方案,因为如果网格将失去焦点,所选项目将失去它们突出显示.
因此,如果您愿意,在网格失去焦点后也会突出显示该选择,您应该重写DataGridRow控件模板,即视觉样式’UnfocusedSelected’.