代码之家  ›  专栏  ›  技术社区  ›  devios1

确定WPF元素相对于某个父元素的边界矩形

  •  15
  • devios1  · 技术社区  · 14 年前

    LayoutInformation.GetLayoutSlot Rect 为0,0,并且不反映元素的实际位置。

    我想做的是用 RenderTargetBitmap

    4 回复  |  直到 14 年前
        1
  •  21
  •   Ray Burns    14 年前

    很简单:

    public static Rect BoundsRelativeTo(this FrameworkElement element,
                                             Visual relativeTo)
    {
      return
        element.TransformToVisual(relativeTo)
               .TransformBounds(LayoutInformation.GetLayoutSlot(element));
    }
    

    事实上,把它放在一个单独的方法中可能有些过分。

        2
  •  7
  •   DanW    9 年前

    LayoutSlot选项对我根本不起作用。

        public static Rect BoundsRelativeTo(this FrameworkElement child, Visual parent)
        {
            GeneralTransform gt = child.TransformToAncestor(parent);
            return gt.TransformBounds(new Rect(0, 0, child.ActualWidth, child.ActualHeight));
        }
    
        3
  •  5
  •   Mauro Sampietro    7 年前

    考虑到我在这里发现的一些建议,这为我解决了问题。

    item.TransformToVisual( relativeToElement )
        .TransformBounds( new Rect( item.RenderSize ) );
    
        4
  •  1
  •   devios1    14 年前

    LayoutInformation.GetLayoutSlot() ActualWidth / ActualHeight RenderSize )以及 UIElement.TranslatePoint() .

    myElement.GetBounds( relativeElement );
    

    哦,好吧。也许是时候用扩展方法了。:)