[英]How to add to Click event to Context Menu buttons in WPF NotifyIcon?
I am making an app that has a notify icon in WPF.我正在制作一个在 WPF 中有通知图标的应用程序。 I am using HardCodet NotifyIcon .
我正在使用HardCodet NotifyIcon 。 They do have a tutorial on code project and it is pretty useful but it does not have any explanation on how to set up
OnClick
or Click
event when the buttons in the context menu are pressed.他们确实有一个关于代码项目的教程,它非常有用,但它没有解释如何设置
OnClick
或按下上下文菜单中的按钮时的Click
事件。
I have gone through every property in NotifyIcon.ContextMenu.Items
and NotifyIcon.ContextMenu.Items.GetItemAt(i)
( TaskbarIcon NotifyIcon = (TaskbarIcon) FindResource("MyNotifyIcon")
) but there is nothing I found.我已经检查了
NotifyIcon.ContextMenu.Items
和NotifyIcon.ContextMenu.Items.GetItemAt(i)
( TaskbarIcon NotifyIcon = (TaskbarIcon) FindResource("MyNotifyIcon")
)中的每个属性,但我什么也没找到。 I also tried typecasting the buttons to MenuItem
and using its Click
event but it didn't help.我还尝试将按钮类型转换为
MenuItem
并使用它的Click
事件,但它没有帮助。
This is my App.xaml
:这是我的
App.xaml
:
<Application.Resources>
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:tb="http://www.hardcodet.net/taskbar">
<tb:TaskbarIcon x:Key="MyNotifyIcon"
ToolTipText="Hello There">
<tb:TaskbarIcon.ContextMenu>
<ContextMenu Background="White">
<MenuItem Header="Open"/>
<MenuItem Header="Settings"/>
<MenuItem Header="Sign Out"/>
<MenuItem Header="Help"/>
<MenuItem Header="Exit"/>
</ContextMenu>
</tb:TaskbarIcon.ContextMenu>
</tb:TaskbarIcon>
</ResourceDictionary>
</Application.Resources>
I need the buttons to control the MainWindow
eg change the Visibility
etc..我需要按钮来控制
MainWindow
,例如更改Visibility
等。
There is no difference to other controls, you can just set up a Click
handler on each MenuItem
.与其他控件没有区别,您只需在每个
MenuItem
上设置一个Click
处理程序。
<MenuItem Header="Open" Click="Open_OnClick"/>
In your example, you would implement the event handler in App.xaml.cs
.在您的示例中,您将在
App.xaml.cs
中实现事件处理程序。
public partial class App : Application
{
// ...application code.
private void Open_OnClick(object sender, RoutedEventArgs e)
{
// ...do something.
}
}
You could also assign a view model as DataContext
to TaskbarIcon
and use a command instead.您还可以将视图 model 作为
DataContext
分配给TaskbarIcon
并改用命令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.