WPF命令与单击事件处理程序

WPF命令与单击事件处理程序

问题描述:

当我使用 Button 中的 Command 控制与点击事件永远不会产生,

When I use the Command in a Buttoncontrol the event handler which joined with Click event will never raised,

如何使用命令 单击事件处理程序

How can I use the Command and handle the Click event handler?

您可以将ICommand附加到另一个属性并从Click处理程序执行它。

You could attach the ICommand to another property and execute it from the Click handler.

<Button x:Name="MyButton" Tag="{x:Static ApplicationCommands.Stop}" Click="MyButton_Click" />

并在处理程序中:

private void MyButton_Click(object sender, RoutedEventArgs e)
{
    var button = sender as Button;
    if (button != null)
    {
        var command = button.Tag as ICommand;
        if (command != null)
            command.Execute(button.CommandParameter);
    }
}

您还需要做一些额外的工作,如果您想要保留命令禁用行为。

You'd also need to do some extra work if you wanted to keep the Command disabling behavior.