如何通过 XAML 中的 CommandParameter 传递当前聚焦的元素名称? [英] How can I pass the currently focused element name through a CommandParameter in XAML?

查看:28
本文介绍了如何通过 XAML 中的 CommandParameter 传递当前聚焦的元素名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 WPF MVVM 应用程序中,我希望能够使用 Esc 键撤消对单个 TextBox 元素的更改.我为此设置了一个命令,因此我想通过 XAML 触发它:

In my WPF MVVM application I want to be able to undo changes to individual TextBox elements using the Esc key. I've set up a command for this and I want to trigger it through XAML thus:

<Window.InputBindings>
    <KeyBinding Command="{Binding EscKeyCommand}" CommandParameter="{Binding FocusManager.FocusedElement}"  Gesture="ESC" />
</Window.InputBindings>

这个想法是 CommandParameter 传递当前聚焦的 TextBox 的 ElementName(如果确实是聚焦的),然后可以在 ViewModel 中处理适当的撤消.我已经尝试了许多 CommandParameter 选项,包括上面的选项,但它们都返回 null.所以,

The idea is that the CommandParameter passes the ElementName of the currently focussed TextBox (if indeed that's what's in focus) and the appropriate undo can then be handled within the ViewModel. I've tried a number of options for the CommandParameter including the one above but they all return null. So,

问题

如何通过 CommandParameter 传递当前聚焦的元素名称?

How can I pass the currently focused element name through a CommandParameter?

推荐答案

很高兴您已经注意到 KeyBoard.FocusedElment.但是这个问题还是有答案的.由于 FocusManager.FocusedElement 是一个附加属性,正确的绑定方法应该是:

I am glad that you have already noticed KeyBoard.FocusedElment. But there still an answer for the question. Since FocusManager.FocusedElement is an attached property, the right way to bind it should be:

CommandParameter="{Binding (FocusManager.FocusedElement), ElementName='name of the window'}"

这篇关于如何通过 XAML 中的 CommandParameter 传递当前聚焦的元素名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆