C# 自定义面板实现:考虑面板的大小';孩子们在安排时
我正在开发一个定制的WPFC# 自定义面板实现:考虑面板的大小';孩子们在安排时,c#,wpf,panel,wpf-positioning,C#,Wpf,Panel,Wpf Positioning,我正在开发一个定制的WPF面板,它的工作原理类似于画布,只是子对象的位置表示为百分比,而不是绝对偏移量。我调用的PercentageCanvas面板将按如下方式使用: <Window> <local:PercentageCanvas> <ChildElement local:PercentageCanvas.Left=".30" local:PercentageCanvas.Top=".50" /> <ChildElement loc
面板
,它的工作原理类似于画布
,只是子对象的位置表示为百分比,而不是绝对偏移量。我调用的PercentageCanvas
面板将按如下方式使用:
<Window>
<local:PercentageCanvas>
<ChildElement local:PercentageCanvas.Left=".30" local:PercentageCanvas.Top=".50" />
<ChildElement local:PercentageCanvas.Left="0" local:PercentageCanvas.Top=".9" />
... etc ...
</local:PercentageCanvas>
</Window>
似乎为了抵消这种中心定位行为,我需要知道每个孩子的尺寸,并在计算Rect
的位置时补偿孩子的大小。但是,我似乎无法访问孩子的大小来计算适当的偏移量
<强>我如何在计算孩子的布局时考虑到孩子的布局在排外> 方法> >/P>> P>在回答问题的过程中找到了答案。所有UIElements
都有一个DesiredSize
属性,它正好提供了我想要的东西。我的ArrangeOverride
方法现在看起来像这样(您必须向右滚动才能看到区别):
元素现在相对于其左上角而不是中心来定位自身
protected override Size ArrangeOverride(Size finalSize)
{
int currentIndex = 0;
for (int index = InternalChildren.Count - 1; index >= 0; index--)
{
Rect rect = new Rect(finalSize);
rect.Location = new Point()
{
X = finalSize.Width * PercentagePanel.GetLeft(InternalChildren[index]) - finalSize.Width / 2,
Y = finalSize.Height * PercentagePanel.GetTop(InternalChildren[index]) - finalSize.Height / 2
};
InternalChildren[index].Arrange(rect);
currentIndex++;
}
return finalSize;
}
protected override Size ArrangeOverride(Size finalSize)
{
int currentIndex = 0;
for (int index = InternalChildren.Count - 1; index >= 0; index--)
{
Rect rect = new Rect(finalSize);
rect.Location = new Point()
{
X = finalSize.Width * PercentagePanel.GetLeft(InternalChildren[index]) - finalSize.Width / 2 + (InternalChildren[index].DesiredSize.Width / 2),
Y = finalSize.Height * PercentagePanel.GetTop(InternalChildren[index]) - finalSize.Height / 2 + (InternalChildren[index].DesiredSize.Height / 2)
};
InternalChildren[index].Arrange(rect);
currentIndex++;
}
return finalSize;
}