说的非常的好:多参考!!!
https://blog.csdn.net/nncrystal/article/details/47416339
https://www.cnblogs.com/dingli/archive/2011/04/22/2024786.html#top
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>
上面代码原文地址:http://www.cnblogs.com/xiaokang088/archive/2011/01/08/1930952.html