2009-07-15 88 views
0

我想为2个按钮使用相同的自定义RoutedCommand,这些按钮位于不同的窗口中。如何定义全局自定义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:无法设置Property Setter'CommandBindings',因为它没有可访问的set访问器。

AFAIK,Window类有一个CommandBindings属性。

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

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

谢谢!

回答

1

由于您将CommandBindings属性(类型为CommandBindingsCollection)的值设置为CommandBinding的实例,因此会显示该错误消息。即使该物业有一个setter(它不),您不能将CommandBinding设置为CommandBindingsCollection

考虑的正常结合命令的情况下:

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

这不是设置CommandBindingCommandBindings财产,而是将它添加到CommandBindings收集Window的。

您是否需要使用RoutedCommand?也许最好使用ICommand的不同实现 - 也许在命令执行时调用delegateKent Boogaart有一个可以工作的实现DelegateCommand(还有很多其他类似的实现也在浮动 - 或者你可以自己编写)。

+0

事实上,你是正确的CommandBindingsCollection和CommandBinding之间的绑定。这就是为什么我第一次尝试(请参阅app.xaml中的注释) 我将在DelegateCommand – rockeye 2009-07-15 12:00:52