2.9講的是,如果內部設定超過容器大小,怎麼辦?
StackPanel會裁剪越界部分
DockPanel和Grid會智能判斷,從而決定換行。
2.10 自定義布局容器
自定義容器要實現兩個方法MeasureOverride和ArrangeOverride,並保證遍歷其下的所有子控件,使 他們都執行Measure和Arrange方法。
using System;
using System.Windows.Controls;
using System.Windows;
namespace CustomPanel {
public class DiagonalPanel : Panel {
protected override Size MeasureOverride( Size availableSize ) {
double totalWidth = 0;
double totalHeight = 0;
foreach( UIElement child in Children ) {
child.Measure( new Size( double.PositiveInfinity,
double.PositiveInfinity ) );
Size childSize = child.DesiredSize;
totalWidth += childSize.Width;
totalHeight += childSize.Height;
}
return new Size( totalWidth, totalHeight );
}
protected override Size ArrangeOverride( Size finalSize ) {
Point currentPosition = new Point( );
foreach( UIElement child in Children ) {
Rect childRect = new Rect( currentPosition, child.DesiredSize );
child.Arrange( childRect );
currentPosition.Offset( childRect.Width, childRect.Height );
}
return new Size( currentPosition.X, currentPosition.Y );
}
}
}