我有一个几乎类似的问题。我的面板必须适合所有的孩子,将它们排成一排并拉伸它们,均匀地填充面板。上面的算法使用渲染变换来缩放元素。问题是渲染变换会拉伸孩子自己,但忽略边距。如果边距较高且比例系数低于 1,则元素会从面板中脱落。您必须根据该轴上的边距校正 RenderTransform 的比例,并使用相同的比例系数进行排列。我使用的 MeasureOverride 是
protected override Size MeasureOverride(Size availableSize)
{
double width = 0; double maxHeight = 0; double mY=0; double mX=0;
Size unlimitedSize = new Size(double.PositiveInfinity, double.PositiveInfinity);
foreach (UIElement child in Children)
{
child.Measure(unlimitedSize);
width += child.DesiredSize.Width;
maxHeight = Math.Max(maxHeight, child.DesiredSize.Height);
FrameworkElement cld = child as FrameworkElement;
mY = cld.Margin.Top + cld.Margin.Bottom;
mX = cld.Margin.Left + cld.Margin.Right;
}
double scaleX = availableSize.Width / width;
double scaleY = availableSize.Height / maxHeight;
//That is scale for arranging
positionScaling = Math.Min(scaleX, scaleY);
try
{
// Let FrameworkElement hight be Xn. mY = Element.Margin.Top + Element.Margin.bottom.
// DesiredSize includes margin therefore:
// (Yn + mY) * scaleY = availableSize.Height
// But render transform doesn't scales margin. Actual render height with margin will be
// Yn * RenderScaleY + mY = availableSize.Height;
// We must find render transform scale coeff like this:
double yn = availableSize.Height / scaleY - mY;
scaleY = (availableSize.Height - mY) / yn;
double xn = availableSize.Width / scaleX - mX;
scaleX = (availableSize.Width - mX) / xn;
scale = Math.Min(scaleX, scaleY); //scale to use in RenderTransform
// In my project all children are similar in size and margin, algorithm BREAKS otherwise!!!
}
catch { scale = 1; }
return availableSize;
}
再一次:在我的项目中,所有孩子的大小和边距都相似,否则算法会中断。