在UserControl

时间:2016-04-17 13:08:40

标签: c# wpf routed-commands

我有一个UserControl,其中有CommandBindings

<UserControl x:Class="DbCreator.UserControls.Menu"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:DbCreator"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
<UserControl.CommandBindings>
    <CommandBinding Command="SelectAll" Executed="SelectAllCommand_Executed"/>
    <CommandBinding Command="local:MyCommands.ToggleNavigator" Executed="ToggleNavigatorCommand_Executed"/>
    <CommandBinding Command="local:MyCommands.ToggleGrid" Executed="ToggleGridCommand_Executed"/>
    <CommandBinding Command="local:MyCommands.SelectNone" Executed="SelectNoneCommand_Executed"/>
</UserControl.CommandBindings>
<Menu Background="White">
    <MenuItem Header="_Файл"/>
    <MenuItem Header="_Правка">
        <MenuItem Header="Выделить всё" Command="SelectAll"/>
        <MenuItem Header="Убрать выделение" Command="local:MyCommands.SelectNone"/>
    </MenuItem>
    <MenuItem Header="_Вид">
        <MenuItem x:Name="ToggleNavigator" Header="Скрыть навигатор" Command="local:MyCommands.ToggleNavigator"/>
        <MenuItem x:Name="ToggleGrid" Header="Скрыть сетку" Command="local:MyCommands.ToggleGrid"/>
    </MenuItem>
    <MenuItem Header="_Диаграмма"/>
    <MenuItem Header="_Справка"/>
</Menu>

当我点击MenuItem时,我的Executed方法被触发,但快捷方式无效。当此UserControl内容是MainWindow代码的一部分时,所有快捷方式都可以完美运行。但我想在单独的文件中定义菜单。

1 个答案:

答案 0 :(得分:1)

所以问题是Menu没有聚焦,也没有收到输入。解决方案是将InputBindings添加到MainWindow

<Window.InputBindings>
    <KeyBinding Command="SelectAll" CommandTarget="{Binding ElementName=Menu}" Key="A" Modifiers="Control"/>
    <KeyBinding Command="local:MyCommands.SelectNone" CommandTarget="{Binding ElementName=Menu}" Key="A" Modifiers="Control+Shift"/>
    <KeyBinding Command="local:MyCommands.ToggleNavigator" CommandTarget="{Binding ElementName=Menu}" Key="N" Modifiers="Alt"/>
    <KeyBinding Command="local:MyCommands.ToggleGrid" CommandTarget="{Binding ElementName=Menu}" Key="G" Modifiers="Alt"/>
</Window.InputBindings>