在没有窗口的WPF应用程序中处理命令

时间:2014-03-11 10:11:47

标签: c# wpf xaml

我正在使用WPF(使用Hardcodet.NotifyIcon.Wpf NuGet包)创建一个托盘应用程序,它在启动时不会显示任何窗口。托盘图标有一个上下文菜单,但我无法将命令绑定到菜单项,因为没有任何东西可以接收命令。我一直在尝试将它们绑定到主应用程序,但它似乎不起作用,CanExecute方法未被调用,因此菜单项被禁用。

我的App.xaml资源字典如下所示:

<ResourceDictionary>
    <ContextMenu x:Key="TrayMenu">
        <MenuItem Header="{x:Static res:AppResources.ContextMenu_AboutLabel}" Command="local:Commands.About" />
        <Separator />
        <MenuItem Header="{x:Static res:AppResources.ContextMenu_ExitLabel}" Command="local:Commands.Exit" /> 
    </ContextMenu>
    <tb:TaskbarIcon x:Key="TaskbarIcon"
        ContextMenu="{StaticResource TrayMenu}"
        IconSource="Application.ico" />
</ResourceDictionary>

代码隐藏只是绑定:

public partial class App
{
    public App()
    {
        InitializeComponent();
        var aboutBinding = new CommandBinding(Commands.About, AboutExecuted, CommandCanExecute);
        var exitBinding = new CommandBinding(Commands.Exit, ExitExecuted, CommandCanExecute);
        CommandManager.RegisterClassCommandBinding(GetType(), aboutBinding);
        CommandManager.RegisterClassCommandBinding(GetType(), exitBinding);
    }

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

    private void AboutExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        Console.WriteLine("About");
    }

    private void ExitExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        Console.WriteLine("Exit");
        Shutdown();
    }
}

我在公共静态类中定义了我的命令,如下所示:

public static class Commands
{
    public static readonly RoutedUICommand About = new RoutedUICommand();
    public static readonly RoutedUICommand Exit = new RoutedUICommand();
}

除了构造函数之外,我没有在任何方法中遇到断点,所以我猜这种方法无论如何都是无效的。我该怎么做?

2 个答案:

答案 0 :(得分:3)

您必须为正确的类注册命令。尝试使用 typeof(Popup)而不是 GetType()

CommandManager.RegisterClassCommandBinding(typeof(Popup), aboutBinding);
CommandManager.RegisterClassCommandBinding(typeof(Popup), exitBinding);

答案 1 :(得分:0)

首先,不希望in ResourceDictionary是任何代码。他的目标是存储控件的样式和资源,而不是代码。

其次,在这种情况下,失去了所有命令的意义,因为它们是为UI和应用程序逻辑之间的独立逻辑创建的。需要在ViewModel类中与View分开定义命令,可能在不同的命名空间中。

第三,使用界面实现ICommand,例如:RelayCommandDelegateCommand。我使用@Josh Smith的界面实现,但通常它是一个品味问题。

有关详细信息,请参阅:

WPF Apps With The Model-View-ViewModel Design Pattern

Understanding Routed Commands

ICommand Interface and RelayCommand Class in WPF MVVM

相关问题