日期:2014-05-18 浏览次数:21156 次
public class SampleLayout : Panel { public SampleLayout() { this.Background = Brushes.Yellow; } protected override Size MeasureOverride(Size availableSize) { double height = 0.0; foreach (UIElement each in InternalChildren) { each.Measure(availableSize); height = Math.Max(height, each.DesiredSize.Height); } return new Size(availableSize.Width, height); } protected override Size ArrangeOverride(Size finalSize) { var desiredWidth = InternalChildren.Cast<UIElement>().Sum(p => p.DesiredSize.Width); if (desiredWidth <= finalSize.Width) { var nextChildLeft = 0.0; foreach (UIElement each in InternalChildren) { each.Arrange(new Rect(new Point(nextChildLeft, 0), each.DesiredSize)); nextChildLeft += each.DesiredSize.Width; } } else { var nextChildLeft = 0.0; var avaWidth = finalSize.Width / InternalChildren.Count; foreach (UIElement each in InternalChildren) { each.Arrange(new Rect(new Point(nextChildLeft, 0), new Size(avaWidth, each.DesiredSize.Height))); nextChildLeft += avaWidth; } } return finalSize; } }
------解决方案--------------------
写反了,如果控件需要的Width大于Panel则均分,否则按期望尺寸显示...
------解决方案--------------------
根本就不需要计算那么麻烦.
放一个grid,然后,有一个元素就增加一列,设置列的最大宽度为你要的数值,然后再设置列宽为*.
这样的话,你的列加的越多,那么每一列酒会压缩的越窄,列越少,则每一列都不会超过最大宽度。
<Grid Width="200" ShowGridLines="True"> <Grid.ColumnDefinitions> <ColumnDefinition MaxWidth="50" Width="*"/> <ColumnDefinition MaxWidth="50" Width="*"/> <ColumnDefinition MaxWidth="50" Width="*"/> <ColumnDefinition MaxWidth="50" Width="*"/> <ColumnDefinition MaxWidth="50" Width="*"/> <ColumnDefinition MaxWidth="50" Width="*"/> <ColumnDefinition MaxWidth="50" Width="*"/> </Grid.ColumnDefinitions> <Label Grid.Column="0">aaaaaaaaaaaaaa</Label> <Label Grid.Column="1">bbbbbbbbbbbb</Label> <Label Grid.Column="2">cccccccccccccc</Label> <Label Grid.Column="3">dddddddddddddd</Label> <Label Grid.Column="4">eeeeeeeeeeeeee</Label> <Label Grid.Column="5">fffffffffffffff</Label> <Label Grid.Column="6">ggggggggggggggg</Label> </Grid>