我正在尝试将我的控件的焦点绑定到视图模型上的属性,如下所示:
public class Focus
{
public static readonly DependencyProperty HasFocusProperty = DependencyProperty.RegisterAttached("HasFocus",
typeof(bool),
typeof(Focus),
new PropertyMetadata(false, HandleHasFocusChanged),
null
);
private static void HandleHasFocusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var uiElement = d as UIElement;
var value = (bool)e.NewValue;
if (value)
{
FocusManager.SetFocusedElement(uiElement, uiElement);
}
}
public static bool GetHasFocus(UIElement obj)
{
return (bool)obj.GetValue(HasFocusProperty);
}
public static void SetHasFocus(UIElement obj, bool value)
{
obj.SetValue(HasFocusProperty, value);
}
}
这适用于第一个焦点,但之后它似乎根本没有任何影响
任何人都知道我做错了什么,甚至是更好的方法来做我想要实现的目标?