通过鼠标事件,从鼠标点击的坐标寻找指定的控件

 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         }
View Code
 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     }
View Code

 

posted @ 2018-07-19 11:40  吃奶嘴的路飞  阅读(487)  评论(0编辑  收藏  举报