【发布时间】:2016-10-12 07:58:38
【问题描述】:
我想为我的应用程序添加一些通用键盘快捷键。目前,在每个 View XAML 中,我都添加了以下代码:
<Window.InputBindings>
<KeyBinding Command="{Binding ZoomInCommand}" Key="Add" Modifiers="Control" />
<KeyBinding Command="{Binding ZoomOutCommand}" Key="Subtract" Modifiers="Control" />
</Window.InputBindings>
为了概括这一点,我想继承 WPF 窗口类并使用新创建的子类。现在我想知道如何将这些键盘命令绑定到相应的代码中。目前它看起来像这样:
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 并对其进行转换,而不是使用 Binding() 对象。如何更改代码以使其看起来更像 MVVM?
【问题讨论】:
标签: c# wpf xaml mvvm data-binding