WPF - Setting ContextMenuItem.Icon

Posted: 03/12/2009

I've been working in my spare time on a organizational quick launch application in Wpf (a set of quick launch items, coherently laid out and organized with the ability to attach active directory groups to items for filtering with a nice UI). Basically, it's a way to organize an organizations services above what the traditional QuickLaunch will do for you. This would be handy for us without the changes to the QuickLaunch bar in Windows 7, but with them it becomes even more useful. I'm not going to go into a length description of the application, but one thing that took me a hour or so to figure out was how to programmatically attach an image to the ContextMenuItem in Wpf. I found lots of examples that did it through the XAML, but none that showed me how I could when I'm dynamically loading menu items from a SQL Server CE database. Here's my VB.NET code (apologies if this doesn't wrap well, Live spaces doesn't handle code well from the Live Writer or I'm too lazy to figure out how to, whichever the case):

Dim imgSource As System.Windows.Media.ImageSource = New System.Windows.Media.Imaging.BitmapImage(New Uri(Globals.ApplicationDataDirectory & s2.ImageFile))
Dim img As New System.Windows.Controls.Image
img.Stretch = Stretch.Uniform
img.Source = imgSource
img.Width = 16
img.Height = 16
contextMenuItem.Icon = img
I had to specifically set the height and width on the icon because I only wanted it to be 16x16 so it looked right on the bar. Otherwise, it tried to stretch it a little too large. There maybe a better way to do this, but this is the first way I actually got it to work so that's what I'm sharing. In a traditional WinForms application we can do this with one line. If anybody knows a better way to programatically do it, feel free to share it.