Sharker Khaleed Mahmud Silverlight Tips & Tricks

August 15, 2010

83. Dynamic Left Click Context Menu in Silverlight

Filed under: Silverlight — Tags: , — Sharker Khaleed Mahmud | shamrat231 @ 9:19 AM

 [tweetmeme source=”shamrat231” only_single=false]

The content used is for demonstration purpose. The idea is simple. Normally we handle context menu for right click event. In this entry, I will use context menu for left click event. So as it is a left click menu, then we can say that the user is actually clicking on something.

You can see the live example here [live demo]   

The SOURCE CODE(.zip) is at the end of the page for download.

Lets create a simple HyperlinkButton and add a context menu.

    <Grid x:Name=”LayoutRoot” Background=”White”>
        <Image Source=”images/background.png” VerticalAlignment=”Top” HorizontalAlignment=”Left” Stretch=”None” />
        <HyperlinkButton Foreground=”Black” FontSize=”12″ HorizontalAlignment=”Left” IsTabStop=”False” FontWeight=”Light” Margin=”200,10,0,0″ MouseEnter=”HyperlinkButton_MouseEnter” Width=”60″ Height=”20″ VerticalAlignment=”Top”>CoolMail</HyperlinkButton>
        <toolkit:ContextMenu x:Name=”myContextMenu” VerticalAlignment=”Top” HorizontalAlignment=”Left” Width=”150″ Visibility=”Collapsed” Margin=”205,25,0,0″ />

Now fill up the our context menu with some data.

myContextMenu.ItemsSource = new string[] { “Inbox”, “Calendar”, “Contacts”, “Send e-mail” };

So when the mouse over, I will show the menu and when we leave the context menu, it will hide it self. So the modified code is…


    public partial class MainPage : UserControl
        public MainPage()
            myContextMenu.ItemsSource = new string[] { “Inbox”, “Calendar”, “Contacts”, “Send e-mail” };
            myContextMenu.MouseLeave += new MouseEventHandler(myContextMenu_MouseLeave);

        void myContextMenu_MouseLeave(object sender, MouseEventArgs e)
            myContextMenu.Visibility = Visibility.Collapsed;

        private void HyperlinkButton_MouseEnter(object sender, MouseEventArgs e)
            myContextMenu.Visibility = Visibility.Visible;

Now this is a bit of a problem, as with dynamic menu item we happen to have no handler. In other words we have to add handlers at runtime using VisualTreeHelper. Lets add a size change handler and find our menu items.

myContextMenu.SizeChanged += new SizeChangedEventHandler(myContextMenu_SizeChanged);

I will use Amyo’s visual tree helper to find all the menu items

List<MenuItem> allMenuItem = GenericVisualTreeHelper.GetAllChildFrameworkElement(myContextMenu)
                .Where(w => w.GetType().Equals(typeof(MenuItem))).Cast<MenuItem>().ToList();

So we got the whole menu collection. Now lets add handler.

        void myContextMenu_SizeChanged(object sender, SizeChangedEventArgs e)
            List<MenuItem> allMenuItem = GenericVisualTreeHelper.GetAllChildFrameworkElement(myContextMenu)
                .Where(w => w.GetType().Equals(typeof(MenuItem)))

            if (allMenuItem.Count() > 0)
                if (!eventAdded)
                    eventAdded = true;
                    foreach (var item in allMenuItem)
                        MenuItem menuItem = (item as MenuItem);
                        if (menuItem != null)
                            menuItem.Click += new RoutedEventHandler(menuItem_Click);
                            menuItem.MouseEnter += new MouseEventHandler(menuItem_MouseEnter);
                            menuItem.MouseLeave += new MouseEventHandler(menuItem_MouseLeave);

In the above code, I am adding click handler for each menu items and in the below code adding some code to execute on each handler.

        void menuItem_MouseLeave(object sender, MouseEventArgs e)
            MenuItem menuItem = (sender as MenuItem);
            menuItem.Icon = null;

        void menuItem_MouseEnter(object sender, MouseEventArgs e)
            MenuItem menuItem = (sender as MenuItem);
            Image icon = new Image();
            icon.Width = 16;
            icon.Source = new BitmapImage(new Uri(“Images/menuOver.png”, UriKind.Relative));
            menuItem.Icon = icon;

        void menuItem_Click(object sender, RoutedEventArgs e)
            MenuItem menuItem = (sender as MenuItem);
            MessageBox.Show(“You just clicked ” + menuItem.Header);

As always, you can download the source code from here [download link]   

Sharker Khaleed Mahmud
Web Developer



  1. […] Dynamic Left Click Context menu in Silverlight (Sharker Khaleed Mahmud) […]

    Pingback by Windows Client Developer Roundup 037 for 8/16/2010 - Pete Brown's — August 16, 2010 @ 6:04 AM

  2. Cool! Looks neat on web pages.

    Comment by boe var — August 22, 2010 @ 11:15 AM

RSS feed for comments on this post. TrackBack URI

Leave a Reply

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

You are commenting using your 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

Create a free website or blog at

%d bloggers like this: