很抱歉问了这个问题,因为我发现了很多类似的问题,但是对它们有效的解决方案似乎不适用于这里…
我有许多自定义控件,它们生成路径(有些是静态的,有些绑定到更新的值)。
我在单个项目控件上显示这些内容(使用画布作为项目模板),并且需要获取各个项目的X&Y位置。下列项目之一的XAML:
<Style TargetType="{x:Type pg:GraphVertexBelt}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type pg:GraphVertexBelt}">
<Border Background="Transparent">
<StackPanel>
<Canvas Width="225" Height="20">
<Ellipse Height="10" Width="10" Canvas.Left="10"/>
<Ellipse Height="10" Width="10" Canvas.Left="220"/>
<Line X1="15" Y1="0.5" X2="225" Y2="0.5"/>
</Canvas>
<Label Content="{Binding Item.Tag.Title}" HorizontalAlignment="Center"/>
</StackPanel>
</Border>
</ControlTemplate>
</Setter>
</Setter>
我遇到的问题是,ActualHeight / ActualWidth总是显示为零。
我试过的:
我需要这样做的原因是,控件中元素的宽度和高度实际上是动态的,我需要能够在相对于实际控件的位置的适当点对图表进行注释。
任何帮助都将不胜感激!
干杯。
编辑
也许我需要更清楚地解释这个意图,这样才有意义。我有一个可缩放的画布,其中显示了一组控件。每个控件都需要放置在画布中,我需要知道这些控件在画布上的高度和宽度。
在每个控件中都有一系列路径(如示例代码所示),这些路径都是相对的,因此我在控件中嵌入了一个画布。控件还具有标签、上下文菜单等。
如果有另外一种更干净的方法来处理这个问题,那么我会全神贯注地听着:)
发布于 2016-06-09 11:19:45
我建议创建自己的画布,并覆盖度量和安排。
public class MyCanvas : Canvas
{
protected override Size MeasureOverride(Size constraint)
{
Size desiredSize = new Size();
foreach (UIElement child in this.Children)
{
// This is your "control"
child.Measure(constraint);
// This is the size of the "control".
var myControlSize = child.DesiredSize;
}
return desiredSize;
}
protected override Size ArrangeOverride(Size arrangeSize)
{
// When this is called, you should know the DesiredSize of each control
// and you can decide where each control location relative to the canvas.
return arrangeSize;
}
}然后使用MyCanvas作为您的ItemsPanelTemplate。
https://stackoverflow.com/questions/37719883
复制相似问题