Panel ArrangeOverride& MeasureOverride方法

时间:2013-10-30 09:06:28

标签: c# wpf panel

有人能为这个功能提供一个简单的例子吗? 我想要实现的是这样的:

当我有一个孩子时 - 我希望全屏显示;

当我有两个孩子时 - 我希望拥有相同的高度和宽度,并在每一行上显示;

当我有3个孩子时,就像这样:

|*************|
|   1  |   2  |
|*************|
|      3      |
|*************|

当我有4个孩子的时候:

|*************|
|   1  |   2  |
|*************|
|   3  |   4  |
|*************|

我怎样才能实现这个目标?

问候。

编辑1:我认为这个面板可以继承UniformGrid somwhow。

1 个答案:

答案 0 :(得分:8)

您似乎无需覆盖MeasureOverride,因为您的面板将占用所有可用空间,因此您只需要在ArrangeOverride中实现您的放置逻辑:

public class CustomPanel : Panel
{
    protected override Size ArrangeOverride(Size finalSize)
    {
        if (Children.Count == 1)
        {
            Children[0].Arrange(new Rect(new Point(0, 0), finalSize));
        }
        else if (Children.Count == 2)
        {
            var halfFinalSize = new Size(finalSize.Width, finalSize.Height/2);
            Children[0].Arrange(new Rect(new Point(0, 0), halfFinalSize));
            Children[1].Arrange(new Rect(new Point(0, finalSize.Height / 2), halfFinalSize));
        }
        else if (Children.Count == 3)
        {
            var halfFinalSize = new Size(finalSize.Width, finalSize.Height / 2);
            var quarterSize = new Size(finalSize.Width / 2, finalSize.Height / 2);

            Children[0].Arrange(new Rect(new Point(0, 0), halfFinalSize));
            Children[1].Arrange(new Rect(new Point(0, finalSize.Height / 2), quarterSize));
            Children[2].Arrange(new Rect(new Point(finalSize.Width / 2, finalSize.Height / 2), quarterSize));
        }
        else if (Children.Count == 4)
        {
            var quarterSize = new Size(finalSize.Width / 2, finalSize.Height / 2);
            Children[0].Arrange(new Rect(new Point(0, 0), quarterSize));
            Children[1].Arrange(new Rect(new Point(finalSize.Width / 2, 0), quarterSize));
            Children[2].Arrange(new Rect(new Point(0, finalSize.Height / 2), quarterSize));
            Children[3].Arrange(new Rect(new Point(finalSize.Width / 2, finalSize.Height / 2), quarterSize));
        }
        else if (Children.Count > 4)
        {
            //???
        }

        return base.ArrangeOverride(finalSize);
    }
}`

PS:确保儿童数量少于5