[英]TransformToAncestor giving me the wrong transform
我是WPF的新手,所以這可能是一個新手問題。 我正在某種圖表編輯器上工作,並且想用線連接一些元素。 這些元素中的某些元素將嵌套在其他元素中,並且單行可能會越過不同級別的元素。 因此,我要在頂層父元素的OnRender
事件中繪制這些線。 這是一個初步的嘗試,在這里我不是在線條上而是在按鈕周圍使用正方形,只是為了確保能夠正確定位子元素:
public class Container : Border
{
public readonly StackPanel Panel = new StackPanel();
private readonly Pen _Pen = new Pen(Brushes.Red, 2);
public Container()
{
Panel.Orientation = Orientation.Vertical;
Panel.Children.Add(MakeButton("One"));
Panel.Children.Add(MakeButton("Two"));
Panel.Children.Add(MakeButton("Three"));
Child = Panel;
}
private Rect GetRect(Visual parent, FrameworkElement element)
{
return element.TransformToAncestor(parent).TransformBounds(LayoutInformation.GetLayoutSlot(element));
}
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
foreach (Button item in Panel.Children)
{
var box = GetRect(this, item);
dc.DrawRectangle(Brushes.Transparent, _Pen, box);
}
}
private static Button MakeButton(string text)
{
Button button = new Button();
button.Content = text;
button.Padding = new Thickness(10);
button.Margin = new Thickness(5);
return button;
}
}
但這我得到的結果是:
如果我在GetRect
方法element.TransformToAncestor(parent).TransformBounds(LayoutInformation.GetLayoutSlot(element))
替換為LayoutInformation.GetLayoutSlot(element)
,則看起來應該是這樣,但這僅是因為繪圖發生在按鈕的直接父級。 在我的實際應用程序中,直接父級不會繪制圖形,因此我需要能夠相對於任意父級獲取插槽。
好,我知道了。 由於GetLayoutSlot
獲取相對於父級的插槽,並且TransformToAncestor
包括子級到父級的關系,因此它將子級元素到父級的距離增加了一倍。 因此,更改GetRect
以從元素的父級獲取祖先可以解決此問題:
private Rect GetRect(Visual ancestor, FrameworkElement element)
{
Visual parent = element.Parent as Visual;
var transform = parent.TransformToAncestor(ancestor);
var slot = LayoutInformation.GetLayoutSlot(element);
return new Rect(transform.Transform(slot.TopLeft), slot.Size);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.