如何在WPF中添加自定义路由命令?

我有一个包含菜单和子菜单的应用程序。我已经将Appliocation命令附加到了某些子菜单项,例如剪切,复制和粘贴。

我还有一些其他菜单项没有应用程序命令。

如何为这些子菜单项添加自定义命令绑定?

我已经阅读了这篇文章,但无法将事件附加到我的子菜单项。

回答:

我使用放置在Window1类(或窗口类恰好被命名的任何类)之后的静态类,在其中创建RoutedUICommand类的实例:

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类所在的名称空间在窗口标记中添加名称空间:

xmlns:w="clr-namespace:NameSpaceOfTheApplication"

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

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

并使用菜单中的绑定,例如:

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

以上是 如何在WPF中添加自定义路由命令? 的全部内容, 来源链接: utcz.com/qa/420692.html

回到顶部