WPF命令,如何声明应用程序级别的命令? [英] WPF Commands, How to declare Application level commands?

查看:74
本文介绍了WPF命令,如何声明应用程序级别的命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有兴趣创建可在WPF应用程序中任何位置使用的命令.

I'm interested in creating commands that are available from anywhere in my WPF application.

我希望它们以与CutCopyPaste和其他应用程序级别命令相同的方式工作,即:

I'd like them to work in the same way as Cut, Copy, Paste and the other Application level commands, ie:

<Button Command="Paste" />

我假设我可以为Application实例设置CommandBindings,但是该属性不可用.

I assumed I could setup CommandBindings for the Application instance, but that property isn't available.

这是怎么做的?

到目前为止,我所能完成的最好的事情就是在顶层窗口上创建一组命令,然后像这样访问它们:

The best I have managed so far is to create a suite of commands on the top level window and then access them like this...:

<Button Command="{x:Static namespace::MainWindow.CommandName}" />

这是可行的,但是当然是紧密耦合的,所以非常脆弱.

Which works, but is of course tightly coupled, and so extremely brittle.

推荐答案

您可以为WPF应用程序的所有Windows"设置CommandBindings,并在Application类中实现命令处理程序.

You can setup CommandBindings for "All Windows" of your WPF application and implement command handlers in Application class.

首先,创建一个静态命令容器类.例如,

First of all, create a static command container class. For example,

namespace WpfApplication1 
{
    public static class MyCommands
    {
        private static readonly RoutedUICommand doSomethingCommand = new RoutedUICommand("description", "DoSomethingCommand", typeof(MyCommands));

        public static RoutedUICommand DoSomethingCommand
        {
            get
            {
                return doSomethingCommand;
            }
        }
    }
}

接下来,将自定义命令设置为Button.Command像这样.

Next, set your custom command to Button.Command like this.

<Window x:Class="WpfApplication1.MainWindow"
        ...
        xmlns:local="clr-namespace:WpfApplication1">
    <Grid>
        ...
        <Button Command="local:MyCommands.DoSomethingCommand">Execute</Button>
    </Grid>
</Window>

最后,在Application类中实现自定义命令的命令处理程序.

Finally, implement the command handler of your custom command in Application class.

namespace WpfApplication1 
{

    public partial class App : Application
    {
        public App()
        {
            var binding = new CommandBinding(MyCommands.DoSomethingCommand, DoSomething, CanDoSomething);

            // Register CommandBinding for all windows.
            CommandManager.RegisterClassCommandBinding(typeof(Window), binding);
        }

        private void DoSomething(object sender, ExecutedRoutedEventArgs e)
        {
            ...
        }

        private void CanDoSomething(object sender, CanExecuteRoutedEventArgs e)
        {
            ...
            e.CanExecute = true;
        }
    }
}

这篇关于WPF命令,如何声明应用程序级别的命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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