WPF从鼠标位置获得视觉效果

时间:2012-10-03 09:54:06

标签: wpf adorner

我有一个画布,其中绘制一些GraphNodes并将它们作为ContentControls添加到画布。所有图形节点都有一个装饰器,我用它来绘制从一个节点到另一个节点的连接线。装饰者有一个方法OnMouseUp:

protected override void OnMouseUp(System.Windows.Input.MouseButtonEventArgs e)
{
    var SourceNode = AdornedElement;
    Point pt = PointToScreen(Mouse.GetPosition(this));
    var DestinationNode = ???
}

此时我有源节点,我开始在AdornedElement中绘制线,这是最初的GraphNode。另外,我有释放鼠标的坐标。在这一点下是另一个GraphNode。如何找到这一点下的节点?

谢谢。

1 个答案:

答案 0 :(得分:0)

好的,经过多次研究后我找到了解决方案:

protected override void OnMouseUp(System.Windows.Input.MouseButtonEventArgs e)
{ 
   Point pt = PointToScreen(Mouse.GetPosition(this));
   UIElement canvas = LogicalTreeHelper.GetParent(AdornedElement) as UIElement;
   // This is important to get the mouse position relative to the canvas, otherwise it won't work
   pt = canvas.PointFromScreen(pt);
   VisualTreeHelper.HitTest(canvas, null, HitTestResultCallbackHandler, new PointHitTestParameters(pt));            
}

然后使用HitTest方法找到GraphNode。请记住,GraphNode是一个自定义对象。

public HitTestResultBehavior HitTestResultCallbackHandler(HitTestResult result)
{
   if (result != null)
   {
      // Search for elements that have GraphNode as parent
      DependencyObject dobj = VisualTreeHelper.GetParent(result.VisualHit);
      while (dobj != null && !(dobj is ContentControl))
      {
         dobj = VisualTreeHelper.GetParent(dobj);
      }
      ContentControl cc = dobj as ContentControl;   
      if (!ReferenceEquals(cc, null))
      {
         IEnumerable<DependencyObject> dependencyObjects = cc.GetSelfAndAncestors();
         if (dependencyObjects.Count() > 0)
            {
                IEnumerable<ContentControl> contentControls = dependencyObjects.Where(x => x.GetType() == typeof(ContentControl)).Cast<ContentControl>();
                if (contentControls.Count() > 0)
                    {
                       ContentControl cControl = contentControls.FirstOrDefault(x => x.Content.GetType() == typeof(GraphNode));
                        if (cControl != null)
                        {
                            var graphNode = cControl.Content as GraphNode;
                            if (!ReferenceEquals(graphNode, null))
                            {
                               // Keep the result in a local variable
                               m_DestinationNode = graphNode;
                               return HitTestResultBehavior.Stop;
                            }
                        }                           
                    }
                }
            }               
        }
    m_DestinationNode = null;
    return HitTestResultBehavior.Continue;
}