FrameworkElement.AddLogicalChild(Object) 方法

定義

將所提供的物件加入至此項目的邏輯樹狀結構。

protected public:
 void AddLogicalChild(System::Object ^ child);
protected internal void AddLogicalChild (object child);
member this.AddLogicalChild : obj -> unit
Protected Friend Sub AddLogicalChild (child As Object)

參數

child
Object

要加入的子項目。

範例

下列範例會在 Child 執行自己的視覺層實作的自訂 FrameworkElement 上實作 屬性。 屬性 setter 的設計目的是讓值變更時,會從邏輯樹狀結構中移除舊的值,以及類別特定的視覺效果集合。 屬性值會快取,然後將新的值新增至邏輯樹狀結構與自訂視覺效果集合。

public virtual UIElement Child
{
    get
    {
        return _child;
    }
    set
    {
        if (_child != value)
        {
            //need to remove old element from logical tree
            if (_child != null)
            {
                OnDetachChild(_child);
                RemoveLogicalChild(_child);
            }

            _vc.Clear();

            if (value != null)
            {
                //add to visual
                _vc.Add(value);
                //add to logical
                AddLogicalChild(value);
            }

            //always add the overlay child back into the visual tree if its set
            if (_overlayVisual != null)
                _vc.Add(_overlayVisual);

            //cache the new child
            _child = value;

            //notify derived types of the new child
            if (value != null)
                OnAttachChild(_child);

            InvalidateMeasure();
        }
    }
}
<System.ComponentModel.DefaultValue(GetType(Object), Nothing)>
Public Overridable Property Child() As UIElement
    Get
        Return _child
    End Get
    Set(ByVal value As UIElement)
        If _child IsNot value Then
            'need to remove old element from logical tree
            If _child IsNot Nothing Then
                OnDetachChild(_child)
                RemoveLogicalChild(_child)
            End If

            _vc.Clear()

            If value IsNot Nothing Then
                'add to visual
                _vc.Add(value)
                'add to logical
                AddLogicalChild(value)
            End If

            'always add the overlay child back into the visual tree if its set
            If _overlayVisual IsNot Nothing Then
                _vc.Add(_overlayVisual)
            End If

            'cache the new child
            _child = value

            'notify derived types of the new child
            If value IsNot Nothing Then
                OnAttachChild(_child)
            End If

            InvalidateMeasure()
        End If
    End Set
End Property

備註

針對代表專案之邏輯子專案的物件實作這個方法。 子項目集合的集合維護可以在屬性 getter 或 setter、Changed 事件、建構函式的類別處理中完成,或在集合類型本身內完成。

針對控制項作者,除非可用基底控制項類別的內容模型不適用於您的控制案例,否則在此層級操作邏輯樹狀結構並不是建議的做法。 請考慮在 、 ItemsControlHeaderedItemsControl 層級進行 ContentControl 子類別化。 這些類別會透過專用 API 提供具有特定強制邏輯樹狀結構子項目的內容模型,以及 WPF 控制項中通常想要的其他功能支援,例如透過範本設定樣式。 如需如何使用 LogicalChildrenAddLogicalChild 的詳細資訊,請參閱 WPF 中的樹狀結構

AddLogicalChild 如果在邏輯樹狀結構被另一個進程逐一查看時呼叫,可能會擲回例外狀況。

適用於

另請參閱