Silverlight中右键菜单
xaml页面
<Grid x:Name="LayoutRoot" Background="White" MouseRightButtonDown="LayoutRoot_MouseRightButtonDown"> <Button Content="右键菜单" Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="btnRight" VerticalAlignment="Top" Width="75" /> </Grid>
xaml.cs代码
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Net; 5 using System.Windows; 6 using System.Windows.Controls; 7 using System.Windows.Documents; 8 using System.Windows.Input; 9 using System.Windows.Media; 10 using System.Windows.Media.Animation; 11 using System.Windows.Shapes; 12 13 namespace RightMenu 14 { 15 public partial class MainPage : UserControl 16 { 17 public MainPage() 18 { 19 InitializeComponent(); 20 21 BindMenu(); 22 } 23 24 private void BindMenu() 25 { 26 ContextMenu cm = new ContextMenu();//新建右键菜单 27 MenuItem mi = new MenuItem();//新建右键菜单项 28 mi.Header = "菜单项"; 29 mi.Click += new RoutedEventHandler(mi_Click);//为菜单项注册事件 30 cm.Items.Add(mi); 31 ContextMenuService.SetContextMenu(btnRight, cm);//为控件绑定右键菜单 32 } 33 34 void mi_Click(object sender, RoutedEventArgs e) 35 { 36 MessageBox.Show("右键菜单事件"); 37 } 38 39 40 41 private void LayoutRoot_MouseRightButtonDown(object sender, MouseButtonEventArgs e) 42 { 43 e.Handled = true; //屏蔽默认的右键菜单 44 } 45 } 46 }