Silverlight ContextMenu用法
分别通过后台和前台两种方式说明在Silverlight中右键菜单的使用
首先要安装Silverlight Toolkit,在项目中添加对System.Windows.Controls.Input.Toolkit 程序集的引用
1、直接在XAML中定义右键菜单,在XAML中添加命名空间xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit",下面代码是为StackPanel添加右键菜单
<StackPanel Orientation="Horizontal" > <TextBlock Text="1234" Margin="5,0,0,0"/> <toolkit:ContextMenuService.ContextMenu> <toolkit:ContextMenu> <toolkit:ContextMenu.Items> <toolkit:MenuItem Header="启用" /> <toolkit:MenuItem Header="禁用" /> </toolkit:ContextMenu.Items> </toolkit:ContextMenu> </toolkit:ContextMenuService.ContextMenu> </StackPanel>
2、通过后台代码添加右键菜单,如下
void Loaded(object sender, RoutedEventArgs e) { ContextMenu contextMenu = new ContextMenu(); contextMenu.Background = new SolidColorBrush(Colors.Transparent); MenuItem item1 = new MenuItem(); item1.Header = "红色"; item1.Click += new RoutedEventHandler(item_Click); contextMenu.Items.Add(item1); MenuItem item2 = new MenuItem(); item2.Header = "蓝色"; item2.Click += new RoutedEventHandler(item_Click); contextMenu.Items.Add(item2); MenuItem item3 = new MenuItem(); item3.Header = "绿色"; item3.Click += new RoutedEventHandler(item_Click); contextMenu.Items.Add(item3); ContextMenuService.SetContextMenu(txtName, contextMenu); } void item_Click(object sender, RoutedEventArgs e) { MenuItem item = sender as MenuItem; //ContextMenu parent = item.Parent as ContextMenu; switch (item.Header.ToString()) { case "红色": ellipse1.Fill = new SolidColorBrush(Colors.Red); break; case "蓝色": ellipse1.Fill = new SolidColorBrush(Colors.Blue); break; case "绿色": ellipse1.Fill = new SolidColorBrush(Colors.Green); break; default: break; } }