我想要一个始终绑定(bind)到当前焦点控件的属性。
我见过两种获取当前焦点控件的方法。
一个是使用 Keyboard.FocusedElement。 第二个是遍历可视化树。
因为我想知道每次焦点元素发生变化时,可视化树遍历似乎一直在运行大量代码。
但是 Keyboard.FocusedElement 没有实现 INotifyPropertyChanged。所以我不能正常绑定(bind)它。
有没有办法让它在发生变化时通知我?
(或者通过其他方式让属性始终设置为当前获得焦点的控件?)
注意:显然我可以在每个控件上添加一个事件并让它更新一个属性。但是我有很多控制权。我想避免必须将事件附加到它们中的每一个。
最佳答案
您可以尝试订阅 Keyboard.GotKeyboardFocus Attached Event
Occurs when an element receives keyboard focus.
这是一个订阅此事件 OnStartup 的示例。例如,您可以使用执行此操作的附加行为并更新可以绑定(bind)到的附加属性。
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
EventManager.RegisterClassHandler(typeof(UIElement),
Keyboard.GotKeyboardFocusEvent,
new RoutedEventHandler(Keyboard_GotKeyboardFocus), true);
base.OnStartup(e);
}
private void Keyboard_GotKeyboardFocus(object sender, RoutedEventArgs e)
{
Debug.WriteLine(e.OriginalSource);
}
}
关于c# - 有没有办法绑定(bind)到 Keyboard.FocusedElement?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11367013/