Visual.AddVisualChild Method (Visual)


The .NET API Reference documentation has a new home. Visit the .NET API Browser on to see the new experience.

Defines the parent-child relationship between two visuals.

Namespace:   System.Windows.Media
Assembly:  PresentationCore (in PresentationCore.dll)

Protected Sub AddVisualChild (
	child As Visual


Type: System.Windows.Media.Visual

The child visual object to add to parent visual.

The AddVisualChild method sets up the parent-child relationship between two visual objects. This method must be used when you need greater low-level control over the underlying storage implementation of visual child objects. VisualCollection can be used as a default implementation for storing child objects.

The following example shows how to define custom storage requirements for a visual child. The example uses the AddVisualChild and RemoveVisualChild methods to sets up the parent-child relationship between the parent visual and child. In order for the visual tree to be enumerated correctly, the example provides overridden implementations of the GetVisualChild method and VisualChildrenCount property.


Although it is possible to use VisualCollection to create parent-child relationships between visual objects, it is more efficient to provide your own custom storage implementation when only one child is linked to a parent.

' 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
	Inherits FrameworkElement
	Private _child As DrawingVisual

	Public Sub New(ByVal drawingVisual As DrawingVisual)
		_child = drawingVisual
	End Sub

	Public Property Child() As DrawingVisual
			Return _child
		End Get

		Set(ByVal value As DrawingVisual)
			If _child IsNot value Then
				_child = value
			End If
		End Set
	End Property

	' Provide a required override for the VisualChildrenCount property.
	Protected Overrides ReadOnly Property VisualChildrenCount() As Integer
			Return If(_child Is Nothing, 0, 1)
		End Get
	End Property

	' Provide a required override for the GetVisualChild method.
	Protected Overrides Function GetVisualChild(ByVal index As Integer) As Visual
		If _child Is Nothing Then
			Throw New ArgumentOutOfRangeException()
		End If

		Return _child
	End Function

.NET Framework
Available since 3.0
Return to top