如何在 WPF 中添加自定义路由命令? [英] How do I add a custom routed command in WPF?

查看:19
本文介绍了如何在 WPF 中添加自定义路由命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含菜单和子菜单的应用程序.我已将应用命令附加到一些子菜单项,例如剪切、复制和粘贴.
我还有其他一些没有应用程序命令的菜单项.
如何向这些子菜单项添加自定义命令绑定?
我经历了这个文章但无法将事件附加到我的子菜单项.

I have an application that contains Menu and sub menus. I have attached Appliocation Commands to some of the sub menu items such as Cut, Copy and Paste.
I also have some other menu items that do not have application commands.
How could I add a custom command binding to those sub menu items?
I have gone through this article but unable to attach event to my sub menu items.

推荐答案

我使用一个静态类,该类放在 Window1 类(或任何碰巧命名的窗口类)之后,我在其中创建了 RoutedUICommand 类的实例:

I use a static class that I place after the Window1 class (or whatever the window class happens to be named) where I create instances of the RoutedUICommand class:

public static class Command {

    public static readonly RoutedUICommand DoSomething = new RoutedUICommand("Do something", "DoSomething", typeof(Window1));
    public static readonly RoutedUICommand SomeOtherAction = new RoutedUICommand("Some other action", "SomeOtherAction", typeof(Window1));
    public static readonly RoutedUICommand MoreDeeds = new RoutedUICommand("More deeds", "MoreDeeeds", typeof(Window1));

}

在窗口标记中添加命名空间,使用Window1类所在的命名空间:

Add a namespace in the window markup, using the namespace that the Window1 class is in:

xmlns:w="clr-namespace:NameSpaceOfTheApplication"

现在我可以像为应用程序命令一样为命令创建绑定:

Now I can create bindings for the commands just as for the application commands:

<Window.CommandBindings>
    <CommandBinding Command="ApplicationCommands.Open" Executed="CommandBinding_Open" />
    <CommandBinding Command="ApplicationCommands.Paste" Executed="CommandBinding_Paste" />
    <CommandBinding Command="w:Command.DoSomething" Executed="CommandBinding_DoSomething" />
    <CommandBinding Command="w:Command.SomeOtherAction" Executed="CommandBinding_SomeOtherAction" />
    <CommandBinding Command="w:Command.MoreDeeds" Executed="CommandBinding_MoreDeeds" />
</Window.CommandBindings>

例如使用菜单中的绑定:

And use the bindings in a menu for example:

<MenuItem Name="Menu_DoSomething" Header="Do Something" Command="w:Command.DoSomething" />

这篇关于如何在 WPF 中添加自定义路由命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆