我想爲我的應用程序添加一些通用鍵盤快捷鍵。目前,在每一個視圖XAML我添加以下代碼:在代碼背後的綁定命令到KeyBinding
<Window.InputBindings>
<KeyBinding Command="{Binding ZoomInCommand}" Key="Add" Modifiers="Control" />
<KeyBinding Command="{Binding ZoomOutCommand}" Key="Subtract" Modifiers="Control" />
</Window.InputBindings>
我爲了這個概括,我想繼承WPF窗口類,並使用新創建的子類來代替。現在我想知道如何在相應的代碼中綁定這些Keyboard命令。目前,它看起來像這樣:
public class MyWindow : Window
{
public MyWindow()
{
DataContextChanged += OnDataContextChanged;
}
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
InputBindings.Clear();
var dataContext = DataContext as IZoomableViewModel;
if (dataContext != null)
{
InputBindings.Add(new KeyBinding(dataContext.ZoomInCommand, Key.Add, ModifierKeys.Control));
InputBindings.Add(new KeyBinding(dataContext.ZoomOutCommand, Key.Subtract, ModifierKeys.Control));
}
}
}
但這並不右看看我,因爲我需要直接訪問到DataContext並投它,而不是使用綁定()的對象。我如何更改代碼以使其看起來更像MVVM?