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

标签 c# wpf xaml

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

代码隐藏只是绑定(bind):

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)静态类中定义了我的命令:

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

除构造函数外,我没有在任何方法中设置断点,所以我猜这种方法不知何故无效。我应该怎么做?

最佳答案

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

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

关于c# - 在没有窗口的 WPF 应用程序中处理命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22322558/

相关文章:

xaml - 如何阻止 Android ScrollViewer 将其自身滚动到其第一个按钮子项

c# - WPF DataGrid 在渲染期间缓慢加载

c# - XAML- 如何将图像添加到 <TabControl> 标记

c# - 加载的 XAML 未正确绑定(bind)到现有元素

c# - 如何在 WP7 上的 SQL 数据库中存储图像

c# - 您将如何在 C# 3.0 中构建桌面应用程序

c# - 我可以在 ASP net core 中返回 504 HTTP 代码吗

c# - 未处理的异常后终止应用程序

c# - 如果数据库中的值发生变化,如何持续更新该值

c# - 从混合了 XML 和纯文本的流中读取