Silverlight4 toolkit 提供了ContextMenu和MenuItem控件来实现右键菜单,下面是效果图
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 <Canvas x:Name="LayoutRoot"> 2 <Border Height="30" Name="bType" Width="90" Canvas.Left="96" BorderThickness="1" BorderBrush="Gray" Background="Transparent" MouseLeftButtonDown="Border_MouseLeftButtonDown" MouseMove="Border_MouseMove" MouseLeftButtonUp="mouseLeftUp"> 3 <sdk:Label Name="lbSencond" HorizontalAlignment="Center" Content="类型" /> 4 <my:ContextMenuService.ContextMenu> 5 <my:ContextMenu Name="TypeMenu" Background="Transparent"> 6 <my:MenuItem Header="植物" Click="TypeMenu_Click"> 7 <my:MenuItem.Icon> 8 <Image Width="16" Height="16" Source="images/zhiwu.jpg" /> 9 </my:MenuItem.Icon> 10 </my:MenuItem> 11 <my:Separator /> 12 <my:MenuItem Header="动物" Click="TypeMenu_Click"> 13 <my:MenuItem.Icon> 14 <Image Width="16" Height="16" Source="images/dongwu.jpg" /> 15 </my:MenuItem.Icon> 16 </my:MenuItem> 17 </my:ContextMenu> 18 </my:ContextMenuService.ContextMenu> 19 </Border> 20 </Canvas>
下面是cs代码
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 private bool isDrag; 2 private Point startPoint; 3 private Point endPoint; 4 5 public MainPage() 6 { 7 InitializeComponent(); 8 9 } 10 11 private void TypeMenu_Click(object sender, RoutedEventArgs e) 12 { 13 MenuItem item = (MenuItem)sender; 14 switch (item.Header.ToString()) 15 { 16 case"动物": 17 MessageBox.Show(item.Header.ToString()); 18 break; 19 case"植物": 20 MessageBox.Show("类型是植物"); 21 break; 22 default: 23 break; 24 } 25 TypeMenu.IsOpen = false; 26 } 27 28 private void mouseLeftUp(object sender, MouseButtonEventArgs e) 29 { 30 isDrag = false; 31 } 32 33 34 35 36 private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) 37 { 38 Point p = e.GetPosition(LayoutRoot); 39 SetDrag(p, bType); 40 } 41 42 private void Border_MouseMove(object sender, MouseEventArgs e) 43 { 44 if (isDrag) 45 { 46 endPoint = e.GetPosition(LayoutRoot); 47 48 Position(endPoint, bType); 49 } 50 } 51 52 private void Position(Point end, UIElement uiName) 53 { 54 //计算X、Y轴起始点与终止点之间的相对偏移量 55 double x = end.X - startPoint.X; 56 double y = end.Y - startPoint.Y; 57 58 Point positon = new Point((double)Canvas.GetLeft(uiName), (double)Canvas.GetTop(uiName)); 59 positon.X += x; 60 positon.Y += y; 61 62 Canvas.SetLeft(uiName, positon.X); 63 Canvas.SetTop(uiName, positon.Y); 64 startPoint = end; 65 } 66 67 private void SetDrag(Point start, UIElement uiName) 68 { 69 isDrag = true; 70 startPoint = start; 71 uiName.CaptureMouse(); 72 }