DataGrid CurrentItem != SelectedItem after reentry with tab-button

流过昼夜 提交于 2020-01-12 19:16:29

问题


This simple WPF-DataGrid

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

which shows a binded list without problems, behaves in a strange way when getting the focus back: First of all a row is selected by the user which makes the datagrid show that row in the selected way (SelectedItem and also CurrentItem contain the selected object). Then the focus is given to another control. In this status - the selection is still shown - SelectedItem is still there while CurrentItem is null! And then the focus comes back by using the TAB-Button. That makes the CurrentItem to be the first object that is shown while the SelectedItem isn't changed. So CurrentItem doesn't go together with SelectetItem in that state which is to be seen in the DataGrid. And I think to myself whats that good for...

My qustion is: How to advice the DataGrid to have the same CurrentItem that was selected before the focus was lost? And how is it possible to synchronize CurrentItem und SelectedItem?

I hope for a simple solution! You would help me a lot. Thanks in advance...


回答1:


Usually I bind the SelectedItem to a property in the DataContext, and set IsSynchronizedWithCurrentItem to false.

<DataGrid ItemsSource="{Binding SomeCollection}"
          SelectedItem="{Binding SelectedItem}" />

Setting IsSyncrhonizedWithCurrentItem to true will make it so the SelectedItem of the Control is synchronized with the CurrentItem property of a collection, however I've had issues with this since I don't always understand how CurrentItem gets and maintains its value.




回答2:


Two ways to resolve this:

  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}" />
    


来源:https://stackoverflow.com/questions/9297665/datagrid-currentitem-selecteditem-after-reentry-with-tab-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!