I created a WPF application with NotifyIcon for working in the tray.

 public partial class MainWindow : Window { public NotifyIcon NotifyIcon { get; } = new NotifyIcon { Icon = Properties.Resources.status_on_ico, Visible = true }; public MainWindow() { InitializeComponent(); NotifyIcon.ContextMenuStrip = MyContextMenuStrip; NotifyIcon.Click += NotifyIcon_Click; } private void Window_Closing(object sender, CancelEventArgs e) { e.Cancel = true; WindowState = WindowState.Minimized; } private void NotifyIcon_Click(object sender, EventArgs e) { Show(); } } 

The XAML of the main window is trivial and irrelevant.

I want to create a ContextMenuStrip for NotifyIcon in XAML (I know how to do this in C # code, but I don't want to).

Here's what I got.

 <WindowsFormsHost> <wf:ContextMenuStrip x:Name="MyContextMenuStrip" TopLevel="False"> <wf:ContextMenuStrip.Items> <!-- Как сюда добавлять элементы --> </wf:ContextMenuStrip.Items> </wf:ContextMenuStrip> </WindowsFormsHost> 

The question is how to add elements to ContextMenuStrip.Items with Name and the Click event handler in XAML?

  • It did not look: stackoverflow.com/a/1472655/6766879 ? There in the source code there are examples of use. - Andrei NOP
  • I watched, but I’m not sure about the viability and reliability of this component, and I don’t see any reason to risk it (since I need basic functionality). - Vadim Ovchinnikov
  • In general, the question of creating a context menu from Windows Forms in XAML, in C #, is easier than ever (therefore, the question is more likely to make it more beautiful, not how to do it somehow). In general, Windows Forms components feel great in WPF and I am not a fan of WPF cleanliness. - Vadim Ovchinnikov
  • Well, judging by the MSDN ContextMenuStrip.Items does not have a setter, so you cannot write anything in the markup, if I'm not mistaken. - Andrei NOP
  • association: stackoverflow.com/q/44390493/1548895 - Vadim Ovchinnikov

1 answer 1

Got a response in English. SO .

The question is how to add elements to ContextMenuStrip.Items with Name and the Click event handler in XAML?

Try it:

 <WindowsFormsHost> <wf:ContextMenuStrip x:Name="MyContextMenuStrip" TopLevel="False"> <wf:ContextMenuStrip.Items> <wf:ToolStripMenuItem Text="test1" Click="It_Click" /> <wf:ToolStripMenuItem Text="test2" /> </wf:ContextMenuStrip.Items> </wf:ContextMenuStrip> </WindowsFormsHost> 

 private void It_Click(object sender, EventArgs e) { MessageBox.Show("click!"); }