WPF Lessons Learned – Use ContextMenu.Items over ContextMenu.ItemsSource

I’ve been working on a WPF project for a client and have learned a lot in the process. I’d like to touch on some of these things. This first post will be about creating a ContextMenu.

I’ve had to create more than one custom ContextMenu for this project. In my first attempt, I created a List<MenuItem> and added all of the MenuItems I wanted in my ContextMenu to this List. Then I created a new ContextMenu and set the ItemsSource to the List. In the MenuItems’ Click event I would need access to the UI element that opened the menu, but when I went to try to get at this element I found that the MenuItem.Parent was null.

When I changed my method to creating a new ContextMenu and then adding all of my MenuItems to it by using ContextMenu.Items.Add(), all of them have the ContextMenu as a Parent. ContextMenu has a PlacementTarget property that is the Object that caused the ContextMenu to open, so my problems were solved.

This entry was posted in .Net, C#, WPF. Bookmark the permalink.