开发者

KeyBinding with no modifiers (in UserControl)

I want to execute a command when a key pressed(without modifiers). So, I tried below code:

<UserControl.InputBindings>
    <KeyBinding Key="A" Command="{Binding ACommand}" />
</UserControl.InputBindings>

but, KeyBinding supports not a key but key and modifier.

Now I consider using Behavior and treat KeyDown event. But this is too complex.

Someone knows an easier solution?

Add: Above code is work well in Window.

I find solution in UserControl. (Using .开发者_C百科NET Framework 4)


I do not quite get what your problem is. The code you wrote should work, there is no need to specify modifiers.

I suppose the problem might be your binding or the control you set the key binding on cannot be focused so it won't trigger.


Microsoft doesn't support binding to a normal key that you might press while typing in a text box - unless it has a modifier. You can bind to function keys (like F1) and a few others without a modifier. See: http://msdn.microsoft.com/en-us/library/system.windows.input.keygesture(v=vs.110).aspx

I've come across a blog that says he was able to get around this problem by creating his own KeyGesture class by inheriting from InputGesture and implementing the Matches function. http://dikhi.wordpress.com/2008/06/27/keygesture-doesnt-work-with-alpha-numeric-key/


I figured a way out to set a InputBinding by using only a single Key like "Key.A"

boolean noMod = ModifierKeys == ModifierKeys.None;
KeyBinding inputBinding = new KeyBinding(this, Keys, noMod ? ModifierKeys.Alt : ModifierKeys));
if (noMod)
{
    inputBinding.ClearValue(KeyBinding.ModifiersProperty);
}

That worked for me fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜