为什么这个简单的WPF命令不起作用?

时间:2018-10-21 11:27:32

标签: c# wpf command

我正在尝试将WPF自定义命令添加到控件中。我所做的:

XAML

<Window x:Class="H.I.S.windows.CommandTest"
        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:H.I.S.windows"
        mc:Ignorable="d"
        Title="CommandTest" Height="450" Width="800">
    <Window.CommandBindings>
        <CommandBinding Command="local:CustomCommand.Save" CanExecute ="SaveCommand_CanExecute"  Executed="SaveCommand_Executed" />
    </Window.CommandBindings>
    <Grid>
        <Button Command="local:CustomCommand.Save" Height="50" Width="100">Click me!</Button>
    </Grid>
</Window>

C#

namespace H.I.S.windows
{

    public partial class CommandTest : Window
    {
        public CommandTest()
        {
            InitializeComponent();
        }
        private void SaveCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void SaveCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("Saved");
        }
    }
    public static class CustomCommand
    {
        public static readonly RoutedUICommand Save = new RoutedUICommand(
            "Save",
            "Save",
            typeof(CustomCommand),
            new InputGestureCollection()
                {
                    new KeyGesture(Key.F2)
                }
            );
    }
}

该按钮被禁用(即使在设计模式下也是如此),并且不允许用户单击它。 我刚刚实现了HERE中描述的代码。 我哪里错了?

2 个答案:

答案 0 :(得分:1)

您发布的代码由于以下声明而使我出错,

  <Window.CommandBindings>
          <CommandBinding Command="local:CustomCommand.Save" CanExecute ="CommandBinding_CanExecute"  Executed="CommandBinding_Executed" />
  </Window.CommandBindings>

将其更改为以下内容后,它开始为我工作

   <Window.CommandBindings>
    <CommandBinding Command="local:CustomCommand.Save" CanExecute ="SaveCommand_CanExecute"  Executed="SaveCommand_Executed" />
   </Window.CommandBindings>

代码背后的事件处理程序与xaml中用于CommandBinding的事件处理程序不同。

“ SaveCommand_CanExecute”和“ SaveCommand_Executed”

如上所述进行更改后,它对我有用,当我单击它时,我可以看到带有“已保存”消息的消息框。

希望您不会错过这个。如果有其他原因阻止您,请尝试进一步查看是否显示任何错误,并告诉我们。

答案 1 :(得分:0)

正如@SirRufo在有问题的评论中建议的那样,问题是我为整个WPF窗口和另一个控件中的按钮声明了“ CommandBindings”。

针对这种情况,有2种解决方案:

1:为Button的直接父级声明CommandBindings。

2:设置与命令绑定的控件名称,并添加如下代码以进行控制:

<Window ... x:Name = "windowName" ...>
<Window.CommandBindings>
        <CommandBinding Command="custumCommand:CustomCommands.Save" CanExecute ="CommandBinding_CanExecute"  Executed="CommandBinding_Executed" />
    </Window.CommandBindings>
<Grid>
<StackPanel>
<GroupBox>
<Button Command="custumCommand:CustomCommands.Save" CommandTarget = "{Binding ElementName=windowName}" Content="Save" />
</GroupBox>
</StackPanel>
</Grid>
</Window>

查看Button的“ CommandTarget ”属性。