我想对两个按钮使用相同的自定义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?
谢谢!