带有单击事件处理程序的 WPF 命令

发布于 2024-09-04 18:49:02 字数 157 浏览 1 评论 0原文

当我在 Button 控件中使用 Command 时,与 Click 事件连接的事件处理程序永远不会引发,

我如何使用 命令并处理Click事件处理程序?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

给不了的爱 2024-09-11 18:49:02

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

<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 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" />

and in the handler:

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.

梦回梦里 2024-09-11 18:49:02

命令是一种周事件。命令的好处是您不需要使用事件。实际上,如果您使用 Viewmodel 模式,则根本不需要使用隐藏代码和事件。请参阅中继命令: http: //blog.galasoft.ch/archive/2009/09/26/using-relaycommands-in-silverlight-and-wpf.aspx

A command is a kind of week event. The good thinks about commands is that you do not need to use events. Actually you do not need to use code behind at all and events if you use a Viewmodel pattern. See relay commands: http://blog.galasoft.ch/archive/2009/09/26/using-relaycommands-in-silverlight-and-wpf.aspx

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文