0

I am making an app that has a notify icon in WPF. I am using 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.

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. I also tried typecasting the buttons to MenuItem and using its Click event but it didn't help.

This is my 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 e.g. change the Visibility etc..

thatguy
  • 21,059
  • 6
  • 30
  • 40
Garvit13
  • 5
  • 2

1 Answers1

0

There is no difference to other controls, you can just set up a Click handler on each MenuItem.

<MenuItem Header="Open" Click="Open_OnClick"/>

In your example, you would implement the event handler in 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.

thatguy
  • 21,059
  • 6
  • 30
  • 40
  • Thanks...But when open is clicked I want the visibility of MainWindow to change to Visible I tried `MainWindow.Visibility = Visibility.Visible` but it does nothing...but exit works – Garvit13 Aug 19 '20 at 11:47
  • @Garvit13 that's a whole other question, you can [find the window](https://stackoverflow.com/a/22856913/366064) but the better approach is to avoid event altogether, and use command instead, so you can easily bind the window visibility to the menu item – Bizhan Aug 19 '20 at 11:50