Tuesday, April 6, 2010

Creating MenuItems dynamically

image This approach is for creating context menu programmatically in .NET3.5/WPF. This is useful when menu structure is variable and dependable.

First there is “MyMenuItem” data structure. It maps to single imagemenu item. You create these objects, link together, and pass over to MenuManager. MenuManager would in turn convert them into real windows MenuItems.

 

 

Client Example:

List<MenuItem> menuItems = mMenuManager.Build(new List<MyMenuItem>() { 
new MyMenuItem() { Label = "1111"},
new MyMenuItem() { Label = "1111"},
new MyMenuItem() { Label = "1111"},
});

foreach (MenuItem menuItem in menuItems)
MyContextMenu.Items.Add(menuItem);






Download MenuManager.cs file here:




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace sergeymalyan.blogspot.com
{
public class MyMenuItem
{
public string Label { get; set; }
public Image ImageIcon { get; set; }
public object Tag { get; set; }

public List<MyMenuItem> DeeperItems
{
get { return mDeeperItems; }
set { mDeeperItems = new List<MyMenuItem>(value); }
}

private List<MyMenuItem> mDeeperItems = new List<MyMenuItem>();
}

/// <summary>
/// Created by Sergey Malyan
/// </summary>
class MenuManager
{
#region events
public delegate void MenuClickedDel(MyMenuItem item);
public event MenuClickedDel MenuClicked;

#endregion

public List<MenuItem> Build(List<MyMenuItem> itemsIn)
{
List<MenuItem> items = new List<MenuItem>();

foreach (MyMenuItem item in itemsIn)
{
items.Add(Traverse(item));
}


return items;
}

private MenuItem Traverse(MyMenuItem item)
{
MenuItem menu = new MenuItem();
try
{
menu.Header = item.Label;

if (item.ImageIcon != null)
{
item.ImageIcon.Width = item.ImageIcon.Height = 16;
menu.Icon = item.ImageIcon;
}


foreach (MyMenuItem item2 in item.DeeperItems)
{
menu.Items.Add(Traverse(item2));
}

menu.Tag = item;

if (item.DeeperItems.Count == 0)
{
menu.Click += new System.Windows.RoutedEventHandler(menu_Click);
}

}
catch (Exception ex)
{
throw;
}

return menu;
}

private void menu_Click(object sender, System.Windows.RoutedEventArgs e)
{
MyMenuItem item = ((MenuItem)sender).Tag as MyMenuItem;

if (MenuClicked != null)
MenuClicked(item);

}
}
}



0 comments:

Post a Comment