使用Tab键重新进入时,DataGrid的CurrentItem不等于SelectedItem

8
这个简单的 WPF 数据表格。
<DataGrid AutoGenerateColumns="False" Height="300" HorizontalAlignment="Stretch" 
      VerticalAlignment="Stretch" Name="dgOriginal" Margin="4,12,0,0"
      CanUserAddRows="False" CanUserDeleteRows="False" CanUserReorderColumns="False" IsSynchronizedWithCurrentItem="True" 
      CanUserSortColumns="False" SelectionMode="Single" SelectionUnit="FullRow">
<DataGrid.Columns>
    <DataGridCheckBoxColumn x:Name="col2Checked"/>
    <DataGridTextColumn x:Name="col2Name"/>
    <DataGridTextColumn x:Name="col2Vorname"/>
</DataGrid.Columns>            

带绑定列表的展示没有问题,但当重新获取焦点时表现很奇怪: 首先用户选择了一行,导致datagrid以选定的方式显示该行(SelectedItem和CurrentItem都包含选定的对象)。然后将焦点给另一个控件。在这种状态下,选择仍然显示-SelectedItem仍然存在,而CurrentItem为null!然后通过使用TAB按钮恢复焦点。这将使CurrentItem成为显示的第一个对象,而SelectedItem未更改。因此,在DataGrid中可以看到,CurrentItem与SelectetItem在该状态下不匹配。我想自言自语这有什么好处...

我的问题是:如何建议DataGrid具有与失去焦点之前所选的相同的CurrentItem?并且如何同步CurrentItem und SelectedItem?

我希望有一个简单的解决方案!您会帮助我很多。提前感谢...

2个回答

4
通常我会将SelectedItem绑定到DataContext中的一个属性,并将IsSynchronizedWithCurrentItem设置为false。
<DataGrid ItemsSource="{Binding SomeCollection}"
          SelectedItem="{Binding SelectedItem}" />

设置 IsSyncrhonizedWithCurrentItem 为 true 将会使得控件的 SelectedItem 与集合的 CurrentItem 属性同步,但是我经常遇到问题,因为我并不总是理解 CurrentItem 是如何获取和维护其值的。

谢谢你的帮助!但我担心你的建议无法解决问题:在使用Tab键重新进入后,我仍然看到第一列中标记当前项目行的这个丑陋的小框。如果用户使用键盘在DataGrid中导航,所选行将更改为CurrentItem行,似乎SelectedItem始终跟随CurrentItem... - navigato

1
两种解决方法:

1.

2.

  1. Log a bug report with Microsoft Support, stating that IsSynchronizedWithCurrentItem doesn't always work when you use TAB.

  2. Bind the SelectedItem to the current cell's row, which is stored in the CurrentCell's Item property:

    <DataGrid SelectedItem="{Binding RelativeSource={RelativeSource Self}, Path=CurrentCell.Item, Mode=OneWay}" />
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接