在我的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()无法工作。所以我的问题是:
谢谢
-John
发布于 2017-04-25 14:33:43
在运行GetDescendantBounds之前,我可以强制进行布局计算吗?
是的,调用Arrange和Measure方法的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-25 03:27:26
首先,您需要在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;
}https://stackoverflow.com/questions/43597684
复制相似问题