Export (0) Print
Expand All
1 out of 1 rated this helpful - Rate this topic

How to: Override the Logical Tree

Although it is not necessary in most cases, advanced control authors have the option to override the logical tree.

This example describes how to subclass StackPanel to override the logical tree, in this case to enforce a behavior that the panel may only have and will only render a single child element. This isn't necessarily a practically desirable behavior, but is shown here as a means of illustrating the scenario for overriding an element's normal logical tree.

	Public Class SingletonPanel
		Inherits StackPanel
        'Private _children As UIElementCollection 
		Private _child As FrameworkElement

		Public Sub New()

		End Sub

		Public Property SingleChild() As FrameworkElement

			Get
				Return _child
			End Get
			Set(ByVal value As FrameworkElement)
				If value Is Nothing Then
					 RemoveLogicalChild(_child)
				Else
					 If _child Is Nothing Then
						 _child = value
					 Else
						 ' raise an exception?
						 MessageBox.Show("Needs to be a single element")
					 End If
				End If
			End Set
		End Property
		Public Sub SetSingleChild(ByVal child As Object)
			Me.AddLogicalChild(child)
		End Sub

		Public Shadows Sub AddLogicalChild(ByVal child As Object)
			_child = CType(child, FrameworkElement)
			If Me.Children.Count = 1 Then
				Me.RemoveLogicalChild(Me.Children(0))
				Me.Children.Add(CType(child, UIElement))
			Else
				Me.Children.Add(CType(child, UIElement))
			End If
		End Sub

		Public Shadows Sub RemoveLogicalChild(ByVal child As Object)

			_child = Nothing
			Me.Children.Clear()
		End Sub
		Protected Overrides ReadOnly Property LogicalChildren() As IEnumerator
		   Get
		   ' cheat, make a list with one member and return the enumerator
		   Dim _list As New ArrayList()
		   _list.Add(_child)
		   Return CType(_list.GetEnumerator(), IEnumerator)
		   End Get
		End Property
	End Class

For more information on the logical tree, see Trees in WPF.

Show:
© 2014 Microsoft. All rights reserved.