我在面板中有一堆具有相同高度的物品。我希望面板中的项目根据面板本身的最大宽度缩小其宽度。
例如 - 面板的宽度为400,面板中有4个项目,每个项目的宽度为100.如果是2个项目,则每个项目的宽度为200个。
第二次使用项目的预期宽度调用child.Measure
后,child.DesiredSize
会完全更改为其他内容。如何强制项目取宽度我给它?
public class DynamicShrinkPanel : StackPanel
{
public DynamicShrinkPanel()
{
}
protected override Size MeasureOverride(Size constraint)
{
Size desiredSize = new Size();
foreach (UIElement child in InternalChildren)
{
// First call to get the desired size.
child.Measure(constraint);
double properChildWidth = constraint.Width / InternalChildren.Count;
// Second call to set what I want, doesn't do what I expect
child.Measure(new Size(properChildWidth, child.DesiredSize.Height));
desiredSize.Height = child.DesiredSize.Height;
desiredSize.Width += child.DesiredSize.Width;
}
return desiredSize;
}
}
答案 0 :(得分:0)
我弄清楚了,不要使用MeassureOverride
来计算确切的尺寸,而是使用ArrangeOverride
方法。
protected override Size MeasureOverride(Size constraint)
{
Size desiredSize = new Size();
foreach (UIElement child in InternalChildren)
{
child.Measure(constraint);
desiredSize.Height = child.DesiredSize.Height;
desiredSize.Width = constraint.Width;
}
return desiredSize;
}
protected override Size ArrangeOverride(Size arrangeSize)
{
double offset = 0;
double properWidth = arrangeSize.Width / InternalChildren.Count;
foreach (UIElement child in InternalChildren)
{
child.Arrange(new Rect(offset, 0, properWidth, arrangeSize.Height));
offset += properWidth;
}
return arrangeSize;
}