【问题标题】:How to define a global custom RoutedCommand?如何定义全局自定义 RoutedCommand?
【发布时间】:2009-07-15 09:52:53
【问题描述】:

我想对位于不同窗口中的 2 个按钮使用相同的自定义 RoutedCommand。

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

我想过使用 Style 来实现这一点。下面,我在一个简单的示例中重现了我的问题。

我在 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:无法设置属性设置器“CommandBindings”,因为它没有可访问的设置访问器。

AFAIK,Window 类有一个 CommandBindings 属性。

1) 使用 Style 来声明全局 CommandBindings 是否正确?如果没有,我该怎么办?

2) 为什么不能通过样式设置属性CommandBindings?

谢谢!

【问题讨论】:

    标签: wpf routed-commands


    【解决方案1】:

    您收到该错误消息是因为您将CommandBindings 属性(类型为CommandBindingsCollection)的值设置为CommandBinding 的实例。即使该属性有一个设置器(它没有),您也不能将CommandBinding 设置为CommandBindingsCollection

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

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

    这不是将CommandBinding 设置为CommandBindings 属性,而是将其添加到WindowCommandBindings 集合中。

    您必须使用RoutedCommand 吗?也许使用ICommand 的不同实现会更好——也许在执行命令时调用delegateKent Boogaart 有一个可以工作的 DelegateCommand 的实现(还有许多其他类似的实现,或者你可以自己编写)。

    【讨论】:

    • 确实,您适合CommandBindingsCollection 和CommandBinding 之间的绑定。这就是我一开始尝试 的原因(请参阅 app.xaml 中的 cmets)
    • 你是对的。使用 RelayCommand(或 DelegateCommand)要容易得多,并且避免使用 CommandBinding。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-11
    相关资源
    最近更新 更多