Visual.AddVisualChild(Visual) 方法

定義

定義兩個視覺項目之間的父-子關係。

C#
protected void AddVisualChild(System.Windows.Media.Visual child);

參數

child
Visual

要加入至父視覺項目的子視覺物件。

範例

下列範例示範如何定義視覺子系的自訂儲存需求。 此範例會使用 AddVisualChildRemoveVisualChild 方法來設定父視覺效果與 child 之間的父子式關聯性。 為了讓視覺化樹狀結構正確列舉,此範例會提供方法與 VisualChildrenCount 屬性的 GetVisualChild 覆寫實作。

備註

雖然可以使用 VisualCollection 在視覺物件之間建立父子式關聯性,但是當只有一個子系連結到父系時,提供您自己的自訂儲存體實作會更有效率。

C#
// Create a host visual derived from the FrameworkElement class.
// This class provides layout, event handling, and container support for
// the child visual object.
public class MyVisualHost : FrameworkElement
{
    private DrawingVisual _child;

    public MyVisualHost(DrawingVisual drawingVisual)
    {
        _child = drawingVisual;
        this.AddVisualChild(_child);
    }

    public DrawingVisual Child
    {
        get
        {
            return _child;
        }

        set
        {
            if (_child != value)
            {
                this.RemoveVisualChild(_child);
                _child = value;
                this.AddVisualChild(_child);
            }
        }
    }

    // Provide a required override for the VisualChildrenCount property.
    protected override int VisualChildrenCount
    {
        get { return _child == null ? 0 : 1; }
    }

    // Provide a required override for the GetVisualChild method.
    protected override Visual GetVisualChild(int index)
    {
        if (_child == null)
        {
            throw new ArgumentOutOfRangeException();
        }

        return _child;
    }

備註

方法 AddVisualChild 會設定兩個視覺物件之間的父子關聯性。 當您需要對視覺子物件的基礎儲存實作進行更大的低階控制時,必須使用這個方法。 VisualCollection 可作為儲存子物件的預設實作。

適用於

產品 版本
.NET Framework 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

另請參閱