Metro Nuggets

Bitesized tidbits for building Modern (Metro) apps.

Launching a Context Menu From Code

One of the great things the Windows Phone Toolkit brings developers is the ContextMenu and ContextMenuService that allows developers to offer their users a tap and hold menu, the same kind that appears in the OS itself.

Generally, you would create the context menu in xaml and attach it to an item within your page (or DataTemplate), but what if you want the user to be able to tap a button and have it appear? If you create the ContextMenu as normal in xaml then try and launch it from code, you’ll end up with an exception being through that the Element is already a child of another element. But if you create it in code, then it might not appear where you want it to appear, so what then?

The Solution

Although we do have to create it in code, we can at least set what it’s parent is, and you can do that like this:

        private void BtnOpenContext_OnClick(object sender, EventArgs e)
        {
            var contextMenu = ContextMenuService.GetContextMenu(ContentPanel);

            if (contextMenu == null)
            {
                contextMenu = new ContextMenu();
            }
            else
            {
                contextMenu.Items.Clear();
            }

            var helloHermit = new MenuItem
            {
                Header = "Hello Hermit"
            };
            helloHermit.Click += (o, args) => MessageBox.Show("Hello All");

            contextMenu.Items.Add(helloHermit);

            ContextMenuService.SetContextMenu(ContentPanel, contextMenu);

            contextMenu.IsOpen = true;
        }

This code can then be attached to anything, including an AppBar (although for that scenario, I would highly recommend the AppBarPrompt in the Coding4Fun Toolkit instead).

If you want to see that in action, then download a quick sample project http://sdrv.ms/11v5pfV

SL

Advertisements

2 responses to “Launching a Context Menu From Code

  1. Pingback: Launching a Context Menu From Code

  2. Pingback: Windows Store Developer Links – 2013-06-28 | Dan Rigby

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: