开发者

Focus control from ViewModel

Why is the 1st button "active" when I am not hovering o开发者_高级运维ver the button or anything. This seems to happen after I change tabs.

Focus control from ViewModel

I suspect that when I change tabs, it focuses the 1st control. Is that the case? I am developing a MVVM app, so from my view model, how might I focus the text box instead?


Since WPFs concept of focus is kinda complicated, I have a class called FocusEnforcer.

It really really makes sure the desired control gets the focus, no matter what.

public static class FocusEnforcer
{
    public static void EnforceFocus(UIElement element)
    {
        if (!element.Focus())
        {

            element.Dispatcher.BeginInvoke(DispatcherPriority.Input, 
                                            new ThreadStart(delegate()
                                                            {
                                                                element.Focus();
                                                            }));

        }

    }
}


This kind of behavior requires just that: a behavior. Or, at least, a new attached property.

  1. Create an attached property for tab controls.
  2. Create a handler for changes to this attached property.
  3. In this handler, subscribe to the TabControl's SelectionChanged event.
  4. In the SelectionChanged event handler, use the TabControl.FindName method to get the text box.
  5. Execute the FocusManager.SetFocusedElement method using the TabControl as the focus scope.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜