我想为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不能被样式设置?
谢谢!
事实上,你是正确的CommandBindingsCollection和CommandBinding之间的绑定。这就是为什么我第一次尝试(请参阅app.xaml中的注释) 我将在DelegateCommand –
rockeye
2009-07-15 12:00:52