首页 文章

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

提问于
浏览
15

我认为这是一个非常简单的请求,但我似乎无法在搜索中找到确凿的答案 . 如何确定窗口中特定视觉元素相对于其他父元素的边界?

我尝试过使用 LayoutInformation.GetLayoutSlot ,但这似乎只是在0,0处返回 Rect 并且没有反映元素的实际位置 .

我正在尝试做的是使用 RenderTargetBitmap 的一个窗口"screenshot"然后将其裁剪为特定元素,但我可以't get the element'界限知道要将位图裁剪成什么!

4 回答

  • 4

    这很简单:

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

    事实上,将它放在一个单独的方法中可能有点过分 .

  • 17

    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

    没关系,我终于设法使用 LayoutInformation.GetLayoutSlot() (虽然我可能使用了 ActualWidth / ActualHeightRenderSize )和 UIElement.TranslatePoint() 的组合来解决这个问题 .

    当它可以像这样简单时,似乎是一个相当复杂的解决方案:

    myElement.GetBounds( relativeElement );
    

    那好吧 . 也许是扩展方法的时间 . :)

  • 0

    考虑到我在这里找到的一些建议,这解决了我的问题 .

    item.TransformToVisual( relativeToElement )
        .TransformBounds( new Rect( item.RenderSize ) );
    

相关问题