我正在使用 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/