看看这个在左上角排列子元素的非常简单的自定义面板:
public class MyPanel : Panel
{
protected override Size MeasureOverride(Size availableSize)
{
Trace.TraceInformation("MeasureOverride");
var size = new Size();
foreach (UIElement element in InternalChildren)
{
element.Measure(availableSize);
size.Width = Math.Max(size.Width, element.DesiredSize.Width);
size.Height = Math.Max(size.Height, element.DesiredSize.Height);
}
return size;
}
protected override Size ArrangeOverride(Size finalSize)
{
Trace.TraceInformation("ArrangeOverride");
foreach (UIElement element in InternalChildren)
{
element.Arrange(new Rect(element.DesiredSize));
}
return finalSize;
}
}
如果您将它与 Button 子项一起使用,如下所示
<local:MyPanel>
<local:MyPanel>
<Button Width="100" Height="100" Click="Button_Click"/>
</local:MyPanel>
</local:MyPanel>
和一个调整按钮大小的 Button_Click 处理程序
private void Button_Click(object sender, RoutedEventArgs e)
{
((FrameworkElement)sender).Width += 20;
}
您会观察到,在每个按钮上单击都会测量和排列父面板和祖父面板。跟踪输出如下所示:
CustomPanelTest.vshost.exe Information: 0 : MeasureOverride
CustomPanelTest.vshost.exe Information: 0 : MeasureOverride
CustomPanelTest.vshost.exe Information: 0 : ArrangeOverride
CustomPanelTest.vshost.exe Information: 0 : ArrangeOverride
因此无需在父面板上调用Measure
或手动操作。Arrange