HOW TO:建立自訂面板項目
更新: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
}
}
如需完整範例,請參閱建立簡單自訂面板範例。