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

自闭症网瘾萝莉.ら 提交于 2020-07-23 07:30:11

问题


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>

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,

Question

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


回答1:


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'}"



回答2:


FocusManager gives the element with the logical focus. To use FocusManager.FocusedElement the scope needs to provided, in this case the window (this)

IInputElement focusedControl = FocusManager.GetFocusedElement(this);

But In your case since it is a text box that you need the focus of use Keyboard.FocusedElement.

In the view model when you execute EscKeyCommand get the element that has the keyboard focus with the following syntax and clear the text.

UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;


来源:https://stackoverflow.com/questions/53581780/how-can-i-pass-the-currently-focused-element-name-through-a-commandparameter-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!