【发布时间】:2014-03-11 10:11:47
【问题描述】:
我正在使用 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();
}
除了构造函数,我没有在任何方法中打断点,所以我猜这种方法在某种程度上是无效的。我该怎么做?
【问题讨论】:
-
您的问题可能与数据上下文相关。您可以通过使用带有公共静态命令的公共静态类来创建全局命令。如果它适合您的情况。
-
@TYY:我想我已经这样做了。将我的命令定义添加到问题中。这是你的意思吗?