0

在我的 WPF 应用程序中,我在运行时从 XML 动态加载 XAML 绘图。此图是一系列复杂的嵌套画布和几何“路径”(例如):

<?xml version="1.0" encoding="utf-8"?>
<Canvas Width="1593" Height="1515">
    <Canvas.Resources />
    <Canvas>
        <Path Fill="…" Data="…"/>
        <Path Fill="…" Data="…"/>
        <Path Fill="…" Data="…"/>
        <Canvas>
            <Canvas>
                <Path Stroke="…" StrokeThickness="…" StrokeMiterLimit="…" StrokeLineJoin="…" StrokeEndLineCap="…" Data="…"/>
                <Path Stroke="…" StrokeThickness="…" StrokeMiterLimit="…" StrokeLineJoin="…" StrokeEndLineCap="…" Data="…"/>
            </Canvas>
        </Canvas>
        <Path Fill="…" Data="…"/>
        <Path Fill="…" Data="…"/>
        <Path Fill="…" Data="…"/>
    </Canvas>
</Canvas>

外部画布的高度/宽度设置不正确,因为许多路径表达式超出了这些尺寸。我对此源 XML 没有任何控制权,因此我需要在加载图形后在运行时对其进行修复。要加载绘图,我使用类似于以下的代码:

public static Canvas LoadDrawing(string xaml)
{
    Canvas drawing = null;
    using (var stringreader = new StringReader(xaml))
    {
        using (var xmlReader = new XmlTextReader(stringreader))
        {
            drawing = (Canvas)XamlReader.Load(xmlReader);
        }
    }
    return drawing;
}

然后,我尝试使用以下代码重置画布大小:

    var canvas = LoadDrawing(…);
    someContentControOnTheExistingPage.Content = canvas;
    var bounds = VisualTreeHelper.GetDescendantBounds(canvas); // << 'bounds' is empty here.
    canvas.Width = bounds.Width;
    canvas.Height = bounds.Height;

除了,在我创建画布元素的地方,边界是空的。但是,如果我只是连接一个简单的按钮并在同一个画布上交互调用 GetDescendantBounds(),那么我会收到预期的高度/宽度。

我的收获是 GetDescendantBounds() 除非具有新控件的布局已完成,否则它不起作用。所以我的问题是:

  1. 有没有办法在运行 GetDescendantBounds() 之前强制进行布局计算?或者……</li>
  2. 在将视觉树添加到其父级之前,是否有另一种方法可以获取视觉树的边界/范围?

谢谢

-约翰

4

2 回答 2

1

有没有办法在运行 GetDescendantBounds 之前强制进行布局计算?

是的,调用 的ArrangeMeasure方法Canvas

var canvas = LoadDrawing("...");
someContentControOnTheExistingPage.Content = canvas;
canvas.Arrange(new Rect(someContentControOnTheExistingPage.RenderSize));
canvas.Measure(someContentControOnTheExistingPage.RenderSize);
var bounds = VisualTreeHelper.GetDescendantBounds(canvas);
canvas.Width = bounds.Width;
canvas.Height = bounds.Height;
于 2017-04-25T14:33:43.947 回答
0

首先,您需要在您的 xaml 字符串中添加这一行。

xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'

这是用于查找控件和属性的 C# 代码示例。

 public void LoadXaml()
    {
        string canvasString = @"<Canvas Name='canvas1' xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' Width = '1593' Height = '1515'> </Canvas>";
        var canvas = LoadDrawing(canvasString);

        //Use this line you will find height and width.
        Canvas canvasCtrl = (Canvas)LogicalTreeHelper.FindLogicalNode(canvas, "canvas1");

        // var bounds = VisualTreeHelper.GetDescendantBounds(canvas); // << 'bounds' is empty here.

        canvas.Width = canvasCtrl.Width; //bounds.Width;
        canvas.Height = canvasCtrl.Height; //bounds.Height;
    }
于 2017-04-25T03:27:26.137 回答