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.
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.
- Create an attached property for tab controls.
- Create a handler for changes to this attached property.
- In this handler, subscribe to the TabControl's SelectionChanged event.
- In the SelectionChanged event handler, use the TabControl.FindName method to get the text box.
- Execute the FocusManager.SetFocusedElement method using the TabControl as the focus scope.
精彩评论