代码:
public partial class MainWindow : Window
{
public static readonly RoutedCommand TestRoutedCommand = new RoutedCommand();
public MainWindow()
{
InitializeComponent();
CommandBinding testCommandBinding = new CommandBinding(TestRoutedCommand, Test_Executed, Test_CanExecute);
testCommandBinding.PreviewExecuted += Test_PreviewExecuted;
buttonTest.CommandBindings.Add(testCommandBinding);
// WHEN I UNCOMMENT THAT LINE, ONLY THE "Preview" MESSAGEBOX IS SHOWN
//TestRoutedCommand.Execute(null, buttonTest);
// Ok, I understood that part here: http://stackoverflow.com/a/4877259/48729
}
private void Test_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void Test_PreviewExecuted(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("Preview");
}
private void Test_Executed(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("Executed");
}
}
XAML,它是一个测试表单,所以只有那个按钮:
<Button x:Name="buttonTest" Width="30" Height="30">Test</Button>
当我点击&#34;测试&#34;按钮,没有任何反应,没有CanExecute,没有PreviewExecuted,没有执行...
该代码有什么问题?
答案 0 :(得分:1)
在您的代码中创建CommandBinding,它说明如何处理特定命令(TestRoutedCommand),但是您不执行此命令(除非您取消注释您的行)。如果要在按钮单击时执行它,只需执行:
buttonTest.Command = TestRoutedCommand;