代码改变世界

wpf 控件开发基础(6) -单一容器(Decorator)

2010-04-06 23:51  Clingingboy  阅读(3380)  评论(0编辑  收藏  举报

   其实这部分的文章已经很多了,写下来方便自己查询.

wpf内置提供了很多容器(Panel),容器分为多容器和单容器.下面介绍单容器.内置的单容器,大家最熟悉的如Border,其作用用于装饰容器内的元素,单一容器继承自Decorator,下面来看一个未使用装饰器的例子.

 

<Window x:Class="WPFControlTutorialPart6_WPFApp.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:control="clr-namespace:WPF.Controls;assembly=WPF.Controls"
    Title="Window1" Height="300" Width="300">
    <Grid>
            <Button>Hello World</Button>
    </Grid>
</Window>

image

可以看到一个Button控件填充了整个窗体。一般我们只需要显示正常大小的Button即可.

容器计算规则

计算容器的大小是一个递归的过程,永远是先测量(MeasureOverride)子元素,然后通知父元素分配空间.计算好空间后然后排列(ArrangeOverride),如果测量大小过度ArrangeOverride会自动进行修正的.自定义一个单容器来修正上面的布局

public class PixelSnapper : Decorator
{

    protected override Size ArrangeOverride(Size finalSize)
    {
        Point location = this.CalculateOffset(finalSize, this.Child);
        location.X = Math.Round(location.X);
        location.Y = Math.Round(location.Y);
        this.Child.Arrange(new Rect(location, this.Child.DesiredSize));
        return finalSize;
    }

    private Point CalculateOffset(Size finalSize, UIElement ui)
    {
        Point point = new Point(0.0, 0.0);
        if (ui is FrameworkElement)
        {
            FrameworkElement element = ui as FrameworkElement;
            Size desiredSize = element.DesiredSize;
            switch (element.HorizontalAlignment)
            {
                case HorizontalAlignment.Left:
                    point.X = element.Margin.Left;
                    break;

                case HorizontalAlignment.Center:
                    point.X = (((finalSize.Width - desiredSize.Width) + base.Margin.Left) - base.Margin.Right) / 2.0;
                    break;

                case HorizontalAlignment.Right:
                    point.X = (finalSize.Width - element.Margin.Right) - desiredSize.Width;
                    break;
            }
            switch (element.VerticalAlignment)
            {
                case VerticalAlignment.Top:
                    point.Y = element.Margin.Top;
                    return point;

                case VerticalAlignment.Center:
                    point.Y = (((finalSize.Height - desiredSize.Height) + base.Margin.Top) - base.Margin.Bottom) / 2.0;
                    return point;

                case VerticalAlignment.Bottom:
                    point.Y = (finalSize.Height - element.Margin.Bottom) - desiredSize.Height;
                    return point;
            }
        }
        return point;
    }
}

现在布局

image

wpf内置的BulletDecorator.如内置的CheckBox和RadioButton都是BulletDecorator,左边是符号,右侧是Content

image

示例

image