日期:2014-05-18  浏览次数:21168 次

求助如何使用WPF控件自适应宽度
想实现如WIN7下的任务栏效果,截图:

当 只有一两个 控件时 :


当出现很多控件时自动调整宽度如下图:




------解决方案--------------------
WPF在任务栏里不是自适应宽度的吗
------解决方案--------------------
WPF在任务栏属性里设置
------解决方案--------------------
恩,自己写Layout,override measure/arrange
------解决方案--------------------
大概写了一下,如果比Panel尺寸大则正常显示,否则根据数量均分
C# code

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,然后,有一个元素就增加一列,设置列的最大宽度为你要的数值,然后再设置列宽为*.
这样的话,你的列加的越多,那么每一列酒会压缩的越窄,列越少,则每一列都不会超过最大宽度。
C# code

<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>