WPF DataGrid SelectionChanged Object Selection

I am checking inside a change event of a selected dataset. If my condition is satisfied, the code must be executed, and the selected item must be highlighted (or gets focus), if the condition is not met, the control must be returned and the previously selected item must remain selected.

What happens if the condition is not met, the selected element does not change (which works as desired), but the focus is still shifted to the cell selected now, so the element selected by the cell is the previous cell, and focus is the cell that triggered the event .

I tried the datagrid.dispatcher.invoke approach, but it doesn't seem to work. I also tried setting datagrid.selectedindex = e.removeditem [0], which again casts the control to the event with the change, thus putting it in a continuous loop.

Please suggest something.

EDIT :

dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (!IsDirty) { if (e.AddedItems.Count > 0) { SelectedProfile = e.AddedItems[0] as profile; } if (e.RemovedItems.Count > 0) { } } else { MessageBox.Show("Save the profile selected", MessageBoxButton.OK, MessageBoxImage.Warning); return; } } 
+4
source share
2 answers

Prevent cycle.

 void OnSelectionChanged(Object sender, SelectionChangedEventArgs e) { // condition code if (conditionFailed) { datagrid.SelectionChanged -= OnSelectionChanged; datagrid.Selectedindex = e.Removeditem[0]; datagrid.SelectionChanged += OnSelectionChanged; } } 
+2
source

Solved my problem.

What you need to do to enable the dirty flag in the textbox_PreviewKeyDown() event and then do the dirty check in the datagrid_PreviewMouseLeftButtonDown() event.

If the value is dirty, set e.handled=true so that the control skips code execution for this thread.

0
source

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


All Articles