代码之家  ›  专栏  ›  技术社区  ›  rockeye

如何定义全局自定义路由命令?

  •  0
  • rockeye  · 技术社区  · 17 年前

    我想对两个按钮使用相同的自定义routedcommand,它们位于不同的窗口中。

    为了不重复代码,我想在应用程序的某个地方定义命令,并将它绑定到两个按钮上。

    我想用风格来实现这一点。下面,我用一个简单的示例复制我的问题。

    我在app.xaml中声明样式:

    <Application.Resources>
        <Style TargetType="{x:Type Window}">
            <Setter Property="CommandBindings">
            <Setter.Value>
        <!--<Window.CommandBindings>--> <!--I tried with or without this. Doesn't change-->
                    <CommandBinding Command="{x:Static local:App.testBindingCommand}"
                        Executed="OnExecuted" CanExecute="OnCanExecute" />
          <!--</Window.CommandBindings>-->
            </Setter.Value>
            </Setter>
        </Style>
     </Application.Resources> 
    

    以及app.xaml.cs中的自定义命令:

    public static RoutedCommand testBindingCommand = new RoutedCommand();
    
        private void OnExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            System.Windows.MessageBox.Show("OnExecuted");
        }
    
        private void OnCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            System.Windows.MessageBox.Show("OnCanExecute");
    
            e.CanExecute = true;
        }
    

    编译器不喜欢代码并给出错误:

    错误MC3080:无法设置属性setter“commandbindings”,因为它没有可访问的set访问器。

    在afaik中,window类有一个commandbindings属性。

    1)使用样式声明全局commandbindings是否正确?如果没有,我怎么办?

    2)为什么不能按样式设置属性commandbindings?

    谢谢!

    1 回复  |  直到 17 年前
        1
  •  1
  •   Community Mohan Dere    9 年前

    您将收到该错误消息,因为您正在设置 CommandBindings 属性(属于类型 CommandBindingsCollection )到的一个实例 CommandBinding . 即使属性具有setter(它没有),也不能设置 命令绑定 到A 命令绑定集合 .

    通常考虑绑定命令的情况:

    <Window>
        <Window.CommandBindings>
            <CommandBinding Command="{x:Static local:App.testBindingCommand}"
                Executed="OnExecuted" CanExecute="OnCanExecute" />
        </Window.CommandBindings>
    </Window>
    

    这不是设置 命令绑定 命令文件 属性,而不是将其添加到 命令文件 收集 Window .

    你必须使用 RoutedCommand ?也许最好使用不同的 ICommand -可能是一个叫 delegate 执行命令时。 Kent Boogaart 实现了 DelegateCommand 这是可行的(还有很多其他类似的实现也在浮动——或者你可以自己写)。