对WPF中MeasureOverride 和ArrangeOverride 浅理解
以前对MeasureOverride 和ArrangeOverride十分费解,看到了这篇博文茅塞顿开~
1 public class CustomControl1 : Panel 2 { 3 /// <summary> 4 /// 先测量需要多大尺寸,做个申报准备 5 /// </summary> 6 /// <param name="constraint">限定的尺寸,比如,规定了width和height</param> 7 /// <returns></returns> 8 protected override Size MeasureOverride(Size constraint) 9 { 10 //定义预期的宽度和高度 11 double height = 0, width = 0; 12 UIElement element; 13 //遍历每个元素,计算所需的总尺寸 14 for (int i = 0; i < Children.Count; i++) 15 { 16 element = Children[i]; 17 //按照限定的尺寸测量一下自己,拿镜子找着自己 18 element.Measure(constraint); 19 if (height < element.DesiredSize.Height) 20 height = element.DesiredSize.Height; 21 width += element.DesiredSize.Width; 22 } 23 //申报,我需要这个尺寸 24 return new Size(width, height); 25 } 26 27 /// <summary> 28 /// 排列每个元素 29 /// </summary> 30 /// <param name="arrangeBounds">测量的尺寸</param> 31 /// <returns></returns> 32 protected override Size ArrangeOverride(Size arrangeBounds) 33 { 34 double currentX = 100; 35 UIElement element; 36 for (int i = 0; i < Children.Count; i++) 37 { 38 element = Children[i]; 39 //排列每个元素 40 Children[i].Arrange(new Rect(currentX, 0, element.DesiredSize.Width, element.DesiredSize.Height)); 41 currentX += element.DesiredSize.Width; 42 } 43 return arrangeBounds; 44 } 45 }
1 <local:CustomControl1 Width="300" Background="Gray" HorizontalAlignment="Right" Margin="0,20,151,280"> 2 <Rectangle Width="100" Height="50" Fill="Red" Margin="10,10,0,0" /> 3 <Rectangle Width="100" Height="50" Fill="Yellow" Margin="10,10,0,0" /> 4 <Rectangle Width="100" Height="50" Fill="Green" Margin="10,10,0,0" /> 5 </local:CustomControl1>
本文来自xiaokang088的博客,原文地址:http://www.cnblogs.com/xiaokang088/archive/2011/01/08/1930952.html