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

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

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>

可以看到一个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;
    }
}

现在布局

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

示例

相关文章

什么是设计模式一套被反复使用、多数人知晓的、经过分类编目...
单一职责原则定义(Single Responsibility Principle,SRP)...
动态代理和CGLib代理分不清吗,看看这篇文章,写的非常好,强...
适配器模式将一个类的接口转换成客户期望的另一个接口,使得...
策略模式定义了一系列算法族,并封装在类中,它们之间可以互...
设计模式讲的是如何编写可扩展、可维护、可读的高质量代码,...