Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
829 views
in Technique[技术] by (71.8m points)

wpf - Keybinding a RelayCommand

I'm using the RelayCommand in my app. It's great for putting the code in the viewmodel, but how do I bind keystrokes to my command?

RoutedUICommand has its InputGestures property, which makes the command automatically be invoked when I press the keystroke. (As an added bonus, it even makes the keystroke display in the MenuItem.) Unfortunately, there's no reusable interface for RoutedUICommand's extra properties, so I can't make a RelayUICommand that gets the same magic.

I've already tried using InputBindings:

<Window.InputBindings>
    <KeyBinding Key="PageUp" Command="{Binding SelectPreviousLayerCommand}"/>
</Window.InputBindings>

But that gets me a runtime exception, because KeyBinding.Command isn't a dependency property. (Actually, what it complains about is that KeyBinding isn't even a DependencyObject.) And since my RelayCommand is a property on my ViewModel (as opposed to the static field that RoutedUICommand is designed for), databinding is the only way I know of to reference it from XAML.

How have you guys solved this? What's the best way to bind a keystroke to a RelayCommand?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I don't think you can do this from XAML, for exactly the reasons you describe.

I ended up doing it in the code-behind. Although it's code, it's only a single line of code, and still rather declarative, so I can live with it. However, I'd really hope that this is solved in the next version of WPF.

Here's a sample line of code from one of my projects:

this.InputBindings.Add(new KeyBinding(
    ((MedicContext)this.DataContext).SynchronizeCommand,
    new KeyGesture(Key.F9)));

SynchronizeCommand in this case is an instance of RelayCommand, and (obviously) F9 triggers it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...