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

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

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

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

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

问题

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

很高兴你已经注意到了KeyBoard.FocusedElment。但是这个问题仍然有答案。由于FocusManager.FocusedElement是附加的属性,正确的绑定方式应该是:

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

FocusManager 给出具有逻辑焦点的元素。要使用 FocusManager.FocusedElement 需要提供范围,在本例中为 window (this)

IInputElement focusedControl = FocusManager.GetFocusedElement(this);

但是在你的情况下,因为它是一个文本框,你需要使用焦点 Keyboard.FocusedElement

在执行时的视图模型中 EscKeyCommand 使用以下语法获取具有键盘焦点的元素并清除文本。

UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;