Hi
I have a contextmenu that will get its items in runtime. I achieve this by binding a List of strings to ItemSource of ContextMenu. This works fine and will populate my ContextMenu in runtime.
I am now trying to capture left mouse button clicks on the items of the ContextMenu. I do this by adding a handler in code behind. This kind of works aswell, meaning I end up in the handler when clicking on an item in the contextmenu. The problem is that CurrentItem property is always the first item in ContextMenuItems list. Likewise, the CurrentPosition is always 0. So I can not tell which item in the ContextMenu the user has clicked.
MainWindow.xaml
<Window.ContextMenu> <ContextMenu x:Name="myContextMenu" ItemsSource="{Binding Path=ContextMenuItems}"></ContextMenu></Window.ContextMenu>
MainWindow.xaml.cspublic MainWindow(){ vm = new MyViewModel(); this.DataContext = vm; InitializeComponent(); myContextMenu.DataContext = vm; MyNotifyIcon = new System.Windows.Forms.NotifyIcon(); MyNotifyIcon.Icon = new System.Drawing.Icon(@"C:\Images\ps_ikon.ico"); MyNotifyIcon.MouseClick += new System.Windows.Forms.MouseEventHandler(MyNotifyIcon_MouseClick); MyNotifyIcon.Visible = true; myContextMenu.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(OnMenuItemClicked1)); this.Visibility = System.Windows.Visibility.Hidden;}void MyNotifyIcon_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e){ if (e.Button == System.Windows.Forms.MouseButtons.Right) myContextMenu.IsOpen = true;}private void OnMenuItemClicked1(object sender, RoutedEventArgs e){ Console.WriteLine("Clicked: " + ((ContextMenu)sender).Items.CurrentItem.ToString()); e.Handled = true;}MyViewModel.cs
public List<string> ContextMenuItems{ get { return global.Settings.ContextMenuItems; } set { global.Settings.ContextMenuItems = value; RaisePropertyChanged("ContextMenuItems"); }}
Is there a small adjustment to be done to my code that will fix this? Or do I need another approach?I have been working on this issue now for 2 whole days, and read numerous threads etc in search of an answer, but without luck.I am a newbie on WPF so please be gentle :-)