DataGrid CurrentItem! = SelectedItem after re-entry with tab button

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 linked list without problems, behaves in a strange way when focus returns: First of all, a row is selected that causes the datagrid to display this row in the selected way (SelectedItem, as well as CurrentItem contain the selected object). Then the focus is on another control. In this state - the selection is still displayed - SelectedItem is still present, and CurrentItem is null! And then the focus returns using the TAB-Button. This makes CurrentItem the first object that displays until the SelectedItem changes. Therefore, CurrentItem is not combined with SelectetItem in this state, which should be visible in the DataGrid. And I think this is good for ...

My question is: how can I advise a DataGrid to have the same CurrentItem that was selected before the focus was lost? And how can I synchronize CurrentItem und SelectedItem?

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

+4
source share
2 answers

I usually bind 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 the control's SelectedItem synchronize with the CurrentItem property of the collection, however, I had problems with this because I don't always understand how CurrentItem gets and maintains its value.

+2
source

Two ways to solve this problem:

  • Record a bug report with Microsoft support indicating that IsSynchronizedWithCurrentItem does not always work when you use TAB.

  • Bind SelectedItem to the current row of the cell, which is stored in the CurrentCell Item property:

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

Source: https://habr.com/ru/post/1396669/


All Articles