【发布时间】:2017-01-10 01:39:45
【问题描述】:
我在一个面板中有一堆具有相同高度的项目。我希望面板中的项目根据面板本身的最大宽度缩小它们的宽度。
例如 - 面板的宽度为 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;
}
}
【问题讨论】:
-
听起来你可以使用
UniformGrid和Rows="1" -
对,不要为此编写自定义面板。请改用 UniformGrid。
-
UniformGrid 不会自动占据它嵌套的控件的整个宽度。因此,在我的情况下,如果可用宽度为 500,则无论您放入多少物品,它都会使用全部 500。均匀的网格似乎只占用尽可能少的空间。