如何:创建自定义 Panel 元素
更新:2007 年 11 月
示例
本示例演示如何覆盖 Panel 元素的默认布局行为和创建派生自 Panel 的自定义布局元素。
本示例定义一个名为 PlotPanel 的简单的自定义 Panel 元素,该元素依照两个硬编码的 x 和 y 坐标定位子元素。在此示例中,x 和 y 均被设置为 50;因此,所有子元素均放置在 x 和 y 轴上的该位置处。
为了实现自定义的 Panel 行为,此示例使用了 MeasureOverride 和 ArrangeOverride 方法。每个方法均返回定位和呈现子元素所需的 Size 数据。
Public Class PlotPanel
Inherits Panel
'Override the default Measure method of Panel.
Protected Overrides Function MeasureOverride(ByVal availableSize As System.Windows.Size) As System.Windows.Size
Dim childSize As Size = CType(availableSize, Size)
For Each child As UIElement In InternalChildren
child.Measure(childSize)
Next
Return MyBase.MeasureOverride(availableSize)
End Function
Protected Overrides Function ArrangeOverride(ByVal finalSize As System.Windows.Size) As System.Windows.Size
For Each child As UIElement In InternalChildren
Dim x As Double = 50
Dim y As Double = 50
child.Arrange(New Rect(New System.Windows.Point(x, y), child.DesiredSize))
Next
Return MyBase.ArrangeOverride(finalSize)
End Function
End Class
public class PlotPanel : Panel
{
// Default public constructor
public PlotPanel()
: base()
{
}
// Override the default Measure method of Panel
protected override Size MeasureOverride(Size availableSize)
{
Size panelDesiredSize = new Size();
// In our example, we just have one child.
// Report that our panel requires just the size of its only child.
foreach (UIElement child in InternalChildren)
{
child.Measure(availableSize);
panelDesiredSize = child.DesiredSize;
}
return panelDesiredSize ;
}
protected override Size ArrangeOverride(Size finalSize)
{
foreach (UIElement child in InternalChildren)
{
double x = 50;
double y = 50;
child.Arrange(new Rect(new Point(x, y), child.DesiredSize));
}
return finalSize; // Returns the final Arranged size
}
}
有关完整示例,请参见 创建简单自定义面板的示例。