开发者

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

The 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 can I find UIElement CurrentFocusTarget in the above sample?

The long version - Context

We use the XCeed DataGrid in order to show data in different tabs of a lazy-lo开发者_如何转开发aded TabControl. Each tab is lazy-loaded so that the content gets rendered (and, more importantly, the data is fetch) only when the tab is Visible. The whole data flow works great using the MVVM approach.

The problem

Somehow, whenever the user makes changes to a cell and Changes Tab, the databound ViewModel property (that had already been updated) is being set to null.

In order to avoid this, it is possible to call EndEdit() when the focus is lost from the grid.

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

So, my question is:

What is the easiest way to know where the Focus is right now, from the codebehind. I have inspected the FocusManager but can't seem to find the current Focus bearer (or to whom the focus is lost).


FocusManager.GetFocusedElement(Application.Current.MainWindow)

I might need a special case if the DataGrid is not hosted in the 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;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜