通过鼠标事件,从鼠标点击的坐标寻找指定的控件
程序员文章站
2022-04-28 09:52:35
1 /// 2 /// 图片鼠标右键 3 /// 4 /// 5 /// 6 private void Image_slt_MouseRightBu ......
1 /// <summary> 2 /// 图片鼠标右键 3 /// </summary> 4 /// <param name="sender"></param> 5 /// <param name="e"></param> 6 private void Image_slt_MouseRightButtonUp(object sender, MouseButtonEventArgs e) 7 { 8 Point point = e.GetPosition(tree); 9 HitTestResult result = VisualTreeHelper.HitTest(tree, point); 10 if (result == null) 11 return; 12 ListBoxItem item = Utils.FindVisualParent<ListBoxItem>(result.VisualHit); 13 if (item == null) 14 return; 15 var vm_item = item.DataContext as ImageTreeControlImageModel; 16 if (vm_item == null) 17 return; 18 ContextMenu menu = new ContextMenu(); 19 MenuItem mitem = new MenuItem(); 20 mitem.Tag = vm_item; 21 mitem.Click += mItem_Click; 22 mitem.Header = "删除"; 23 menu.Items.Add(mitem); 24 menu.IsOpen = true; 25 }
1 internal static class Utils 2 { 3 public static T FindVisualParent<T>(DependencyObject obj) where T : class 4 { 5 while (obj != null) 6 { 7 if (obj is T) 8 return obj as T; 9 10 obj = VisualTreeHelper.GetParent(obj); 11 } 12 13 return null; 14 } 15 }