MeasureOverride 和ArrangeOverride 浅理解

代码
public class CustomControl1 : Panel
{
/// <summary>
/// 先测量需要多大尺寸,做个申报准备
/// </summary>
/// <param name="constraint">限定的尺寸,比如,规定了width和height</param>
/// <returns></returns>
protected override Size MeasureOverride(Size constraint)
{
//定义预期的宽度和高度
double height = 0, width = 0;
UIElement element;
//遍历每个元素,计算所需的总尺寸
for (int i = 0; i < Children.Count; i++)
{
element
= Children[i];
//按照限定的尺寸测量一下自己,拿镜子找着自己
element.Measure(constraint);
if (height < element.DesiredSize.Height)
height
= element.DesiredSize.Height;
width
+= element.DesiredSize.Width;
}
//申报,我需要这个尺寸
return new Size(width, height);
}

/// <summary>
/// 排列每个元素
/// </summary>
/// <param name="arrangeBounds">测量的尺寸</param>
/// <returns></returns>
protected override Size ArrangeOverride(Size arrangeBounds)
{
double currentX = 100;
UIElement element;
for (int i = 0; i < Children.Count; i++)
{
element
= Children[i];
//排列每个元素
Children[i].Arrange(new Rect(currentX, 0, element.DesiredSize.Width, element.DesiredSize.Height));
currentX
+= element.DesiredSize.Width;
}
return arrangeBounds;
}
}

 

 

代码
<local:CustomControl1 Width="300" Background="Gray" HorizontalAlignment="Right" Margin="0,20,151,280">
<Rectangle Width="100" Height="50" Fill="Red" Margin="10,10,0,0" />
<Rectangle Width="100" Height="50" Fill="Yellow" Margin="10,10,0,0" />
<Rectangle Width="100" Height="50" Fill="Green" Margin="10,10,0,0" />
</local:CustomControl1>

 

posted @ 2011-01-08 22:21  xiaokang088  阅读(2333)  评论(0编辑  收藏  举报