布局的复杂性--深入理解面板类

新建项目SingleCellGridDemo,新增SingleCellGrid.cs类。

 public class SingleCellGrid:Panel
    {

    //MeasureOverride和ArrangeOverride是面板类的两个可重写的方法。第一个是为父元素确定其每个子元素的大小,第二个是父元素把子元素排列到相对于自身的位置上。
protected override Size MeasureOverride(Size availableSize)      //avaliableSize是面板类的父元素可提供的大小。面板类所需的大小是compositSize。
{ Size compositeSize = new Size(); foreach (UIElement child in Children) { child.Measure(availableSize);       //measure用于适当的调整子元素的DesiredSize值。
compositeSize.Width = Math.Min(compositeSize.Width, child.DesiredSize.Width); compositeSize.Height = Math.Min(compositeSize.Height, child.DesiredSize.Height); //Grid面板,将子元素中最大值赋给compositeSize。
} return compositeSize; } protected override Size ArrangeOverride(Size finalSize) { foreach (UIElement child in Children) { child.Arrange(new Rect(new Point(), finalSize));       //Rec表示子元素相对于父元素左上角的位置,以及其大小。
} return base.ArrangeOverride(finalSize); } }

  xaml调用SingleCellGrid类

1     xmlns:local="clr-namespace:SingleCellGridDemo"
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <local:SingleCellGrid>
                <TextBlock Text="TextBlock aligned at right bottom" HorizontalAlignment="Right" VerticalAlignment="Bottom"></TextBlock>
                <Image Source="kauai.jpg"></Image>
                <Ellipse Stroke="{StaticResource PhoneAccentBrush}" StrokeThickness="24"></Ellipse>
                <TextBlock Text="TextBlock aligned at left top" HorizontalAlignment="Left" VerticalAlignment="Top"></TextBlock>         
            </local:SingleCellGrid>
        </Grid>

  

posted on 2012-10-15 14:37  阳光的七夜  阅读(212)  评论(0编辑  收藏  举报