【发布时间】:2017-10-21 21:19:57
【问题描述】:
我正在开发一个使用 MVVM 模式的 WPF 应用程序,而且我对 .NET 开发还很陌生。我的理解是 View 应该将其数据上下文设置为 ViewModel,然后任何与数据相关的处理都应该在 ViewModel 中完成,而 UI 部分应在视图中处理(XAML 或 code behind)。
所以我有一个菜单,每个菜单项都绑定到 DelegateCommand(使用 Prism)在 ViewModel 中声明并使用键盘快捷键进行处理它完美无瑕。但是,我想将菜单项绑定到 View's code behind 文件中的 command,因为它不会处理任何数据(它只是显示或隐藏面板)。
查看 (XAML)
<Window x:Class="Editor.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Editor.Views"
xmlns:vm="clr-namespace:Editor.ViewModels"
mc:Ignorable="d"
x:Name="RootWindow"
WindowStartupLocation="CenterScreen"
Width="1200" Height="650">
<!-- Data Context -->
<Window.DataContext>
<vm:MainViewModel />
</Window.DataContext>
<!-- Keyboard Shortcuts -->
<Window.InputBindings>
<KeyBinding Modifiers="Control" Key="L" Command="{Binding ElementName=RootWindow, Path=ToggleLayersCommand}" />
</Window.InputBindings>
<!-- Main Menu -->
<Menu>
<MenuItem Header="View" Padding="5, 2">
<MenuItem Header="Toggle Layers Panel" InputGestureText="CTRL + L" Command="{Binding ElementName=RootWindow, Path=ToggleLayersCommand}" />
</MenuItem>
</Menu>
</Window>
查看(代码隐藏)
public partial class MainWindow : Window
{
public DelegateCommand ToggleLayersCommand { get; private set; }
public MainWindow()
{
InitializeComponent();
ToggleLayersCommand = new DelegateCommand(ToggleLayersCommand_OnExecuted, () => true);
}
private void ToggleLayersCommand_OnExecuted()
{
LayerListPanel.Visibility = (LayerListPanel.Visibility == Visibility.Collapsed) ? Visibility.Visible : Visibility.Collapsed;
}
}
我在 XAML 中命名窗口以在绑定 Command 属性View 中找到 command 而不是 ViewModel /强>。它似乎找到了它,因为我得到了 intellisense,但它永远不会触发。
我可以使用 click 事件 代替,即使我宁愿使用 command 但是如何绑定 键盘事件的快捷方式?
【问题讨论】: