30 January, 2013

WPF MenuItem programmatically

I seriously don’t know what they had been smoking in Redmond when they invented the URI scheme for WPF. It’s really far from intuitive nor understandable, so if you have set out to create e.g. a ContextMenu programmatically (code over Markup XAML); you are in for a surprise!

Building an editor that required a dynamic tabcontrol (you can add/delete the tabs during runtime); I had to enable a contextmenu associated to these new runtime defined tab items. But, creating these menuitems in code (C#) is not intuitive. So, if you don’t want to spend 1½ hour hunting how to do this, here is how:

        private void NewTab_MouseUp(object sender, MouseButtonEventArgs e)
{
MenuItem editMnu = new MenuItem();
editMnu.Click += editMnu_Click;
editMnu.Header =
"edit";
editMnu.Icon =
new Image { Source = new BitmapImage(new Uri("pack://application:,,,/Images/edit.png", UriKind.Absolute))};

MenuItem delMnu = new MenuItem();
delMnu.Click += delMnu_Click;
delMnu.Header =
"delete";
delMnu.Icon =
new Image { Source = new BitmapImage(new Uri("pack://application:,,,/Images/cancel.png", UriKind.Absolute)) };

ContextMenu cmnu = new ContextMenu();
cmnu.Items.Add(editMnu);
cmnu.Items.Add(delMnu);

(rest omitted)


 


Note the format of the Uri-scheme “pack://applica…..”.! That guy actually points to a location within the application inside the Images folder (see below).


image


Ultimately, you end up with a new tab with this Contextmenu:


image


Who should have known…

1 comment:

Jason Smith said...

"I seriously don’t know what they had been smoking in Redmond when they invented the URI scheme for WPF" - I have complaining about this forever! Thank you for the post though..