How can I determine where Focus * is right now *?

Short version

public class CustomDataGrid : DataGridControl, IXmlSettingsProvider { public CustomDataGrid() { if (DesignModeHelper.IsInDesignMode) return; Loaded += (e, a) => { ... }; LostFocus += (e, a) => { if(IsBeingEdited /* && CurrentFocusTarget.GetType() == typeof(TabControl)*/) EndEdit(); }; } } 

How to find UIElement CurrentFocusTarget in the above example?

Long Version - Context

We use XCeed DataGrid to display data on different tabs of the lazily loaded TabControl. Each tab has a lazy load, so that the content gets visualized (and, more importantly, the data is retrieved) only when the tab is visible. The entire data stream works fine using the MVVM approach.

Problem

Be that as it may, whenever a user makes changes to the cell and the Changes tab , the ViewModel property with the database binding (which has already been updated) is set to null .

To avoid this, you can call EndEdit () when focus is lost from the grid.

However, I only want to call it when focus is lost for TabItem (or TabControl).

So my question is:

Which is the easiest way to find out where the Focus is right now , from the code. I checked FocusManager , but it seems that I could not find the current focus medium (or who lost focus).

+4
source share
1 answer
 FocusManager.GetFocusedElement(Application.Current.MainWindow) 

I might need a special case if the DataGrid is not hosted in Application.Current.MainWindow .

Here is the complete code:

 public class CustomDataGrid : DataGridControl, IXmlSettingsProvider { public BSIDataGrid() { if (DesignModeHelper.IsInDesignMode) return; CommandBindings.Add(new CommandBinding(ResetDataGridLayout, ResetDataGridLayoutExecute, ResetDataGridLayoutCanExecute)); Loaded += (e, a) => { ... }; LostFocus += (e, a) => { if(IsBeingEdited && IsTabFocused()) EndEdit(); }; } private static bool IsTabFocused() { var dependencyObject = FocusManager.GetFocusedElement(Application.Current.MainWindow); return dependencyObject is TabItem; } } 
+4
source

All Articles