简体   繁体   English

托盘图标的 WPF 上下文菜单

[英]WPF ContextMenu for tray icon

I'm having a WPF application which I can minimize to tray.我有一个 WPF 应用程序,我可以将其最小化到托盘。 When I normal-click it, the window shows again.当我正常单击它时,窗口再次显示。

Now I'm wondering how to create a simple ContextMenu ?现在我想知道如何创建一个简单的ContextMenu

The ContextMenu has to get filled with x options which onclick will run a function. ContextMenu必须填充 x 选项,onclick 将运行一个函数。 For now I just need an 'Exit'-item linked to an 'Exit_Click' method.现在我只需要一个链接到“Exit_Click”方法的“退出”项。

Something I've tried is:我试过的东西是:

ContextMenu menu = (ContextMenu)this.FindResource("NotifierContextMenu");
menu.IsOpen = true;

menu doesn't know of any IsOpen value. menu不知道任何IsOpen值。

Other examples like to use a lot of different things.其他例子喜欢使用很多不同的东西。 One of them requires me to create a HostManager for some reason. 其中之一要求我出于某种原因创建一个 HostManager。

I just need a simple ContextMenu .我只需要一个简单的ContextMenu How can I achieve this?我怎样才能做到这一点?

As @HB mentioned Hardcodet's NotifyIcon is pretty darn good for WPF Taskbar icons.正如@HB 提到的, Hardcodet的 NotifyIcon非常适合 WPF 任务栏图标。 Sucks you don't get that out of the box with WPF but you might as well use it and address your issue than wait for Microsoft to fix it(They really should just add that library into standards)糟透了,你没有用 WPF 开箱即用,但你最好使用它并解决你的问题,而不是等待微软修复它(他们真的应该将该库添加到标准中)

Now to solve your issue(Using above solution):现在解决您的问题(使用上述解决方案):

  • Download the solution下载解决方案
  • Build the library建立图书馆
  • Add it to your source control if you have one and add a reference to it( Hardcodet.Wpf.TaskbarNotification.dll ) in your project如果您有,请将其添加到您的源代码管理中,并在您的项目中添加对它的引用( Hardcodet.Wpf.TaskbarNotification.dll

Now in your MainWindow.xaml you could just have something like:现在在您的 MainWindow.xaml 中,您可以拥有以下内容:

<Window ...
        xmlns:tb="http://www.hardcodet.net/taskbar"
        ...>
  ...
  <Grid>
    <tb:TaskbarIcon>
      <tb:TaskbarIcon.ContextMenu>
        <ContextMenu>
          <MenuItem Click="Exit_Click"
                    Header="Exit" />
        </ContextMenu>
      </tb:TaskbarIcon.ContextMenu>
    </tb:TaskbarIcon>
    ...
  </Grid>
</Window>

and MainWindow.xaml.cs with the click handler like you needed:和 MainWindow.xaml.cs 以及您需要的点击处理程序:

private void Exit_Click(object sender, RoutedEventArgs e) {
  Application.Current.Shutdown();
}

I do recommend spending some time looking at the examples coming with the source code of the library to familiarize yourself with your available options.我确实建议花一些时间查看库源代码附带的示例,以熟悉可用选项。 Trust me wpf has it way too easy when it comes to helper libraries.相信我 wpf 在帮助程序库方面太容易了。 Try some of qt helper libraries and you'll know what "buried in there somewhere" literally means in opensource helpers.尝试一些 qt 助手库,你就会知道“埋在某处”在开源助手中的字面意思。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM