Posted by: Zeeshan Amjad | October 26, 2009

Data binding of Context Menu


We just saw that how to make context menu on the tab control. But that menu items is hard coded and fixed. We can make a dynamic menu with the help of data binding. Data binding of menu item is very simple and it is just like binding combo box, list box or any other collection items control. Here is a C# code to make menu with data binding.

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Text;
  5: using System.Windows;
  6: using System.Windows.Controls;
  7: using System.Windows.Data;
  8: using System.Windows.Documents;
  9: using System.Windows.Input;
 10: using System.Windows.Media;
 11: using System.Windows.Media.Imaging;
 12: using System.Windows.Navigation;
 13: using System.Windows.Shapes;
 14: using System.Reflection;
 15: using System.Globalization;
 16: using System.ComponentModel;
 17: 
 18: namespace ContextMenuSample
 19: {
 20:     /// <summary>
 21:     /// Interaction logic for Window1.xaml
 22:     /// </summary>
 23:     public partial class Window1 : Window
 24:     {
 25:         public Window1()
 26:         {
 27:             InitializeComponent();
 28: 
 29:             List<String> menuItems = new List<string>();
 30:             menuItems.Add("Copy");
 31:             menuItems.Add("Cut");
 32:             menuItems.Add("Paste");
 33: 
 34:             ContextMenu cm = new ContextMenu();
 35:             cm.ItemsSource = menuItems;
 36:             tab.ContextMenu = cm;
 37:         }
 38:     }
 39: }
 40: 

Here is a XAML code of this project.

  1: <Window x:Class="ContextMenuSample.Window1"
  2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4:     xmlns:System="clr-namespace:System;assembly=mscorlib"
  5:     xmlns:odp="clr-namespace:objDataProvider"
  6:     Title="Context Menu" Height="300" Width="400">    
  7:     <TabControl Name="tab"  Margin="5">
  8:         <TabItem Header="item 1"/>
  9:         <TabItem Header="item 2"/>
 10:     </TabControl>
 11: </Window>
 12: 

Here is the output of this program.

ContextMenu_03

Advertisements

Responses

  1. […] Menu in List box item We have already seen an example of Context Menu here and here. This time we are going to implement the context menu with list box item. In addition we also […]


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

Categories

%d bloggers like this: