gpt4 book ai didi

wpf - 将元素焦点与附加属性绑定(bind)?

转载 作者:行者123 更新时间:2023-12-03 10:18:53 24 4
gpt4 key购买 nike

我正在尝试将我的控件的焦点绑定(bind)到 View 模型上的属性,如下所示:

 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);
}
}

这适用于第一个焦点,但之后它似乎根本没有任何影响

任何人都知道我做错了什么,甚至是更好的方法来做我想要实现的目标?

最佳答案

逻辑焦点和键盘焦点之间的区别可能会咬你。你可以阅读它here .特别注意关于焦点范围的部分。
当 HasFocus 属性设置为 true 时,您已经实现了将逻辑焦点设置到用户控件的代码,但是当它设置为 false 时您什么也不做。在这种情况下,逻辑焦点将保持在原处。
另一方面,您还没有为用户控件的 lostfocus 事件连接事件处理程序。这意味着当控件失去焦点时,您的 HasFocus 属性将再次不受影响。

关于wpf - 将元素焦点与附加属性绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1841544/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com