WPF Bind to an item generated by Datatemplate using ElementName
Hi Guys,
I have a problem trying to bind to an element created within a datatemplate that is part of a content presenter.
I have attached my XAML with the highlighted sections being the problematic areas. I need to bind my my bespoke behaviour called
local:MyColumnsBindingBehavior.ListBox found in the main content grid to the listbox element name called "listBoxColumns" found in the "columnTemplate" DataTemplate which is part of the "dialogcontent" ContentPresenter.
The basic premise is how to bind to an control generated inside a datatemplate. I am aware of using the VisualTreeHelper like below but don't know how to use it to bind to the control in question:
Private Function FindVisualChild(Of childItem As DependencyObject)(ByVal obj As DependencyObject) As childItem For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(obj) - 1 Dim child As DependencyObject = VisualTreeHelper.GetChild(obj, i) If child IsNot Nothing AndAlso TypeOf child Is childItem Then Return CType(child, childItem) Else Dim childOfChild As childItem = FindVisualChild(Of childItem)(child) If childOfChild IsNot Nothing Then Return childOfChild End If End If Next i Return Nothing End Function
Private Shared Function GetFrameworkElementByName(Of T As FrameworkElement)(referenceElement As FrameworkElement) As T Dim child As FrameworkElement = Nothing For i As Int32 = 0 To VisualTreeHelper.GetChildrenCount(referenceElement) - 1 child = TryCast(VisualTreeHelper.GetChild(referenceElement, i), FrameworkElement) System.Diagnostics.Debug.WriteLine(child) If child IsNot Nothing AndAlso child.[GetType]() = GetType(T) Then Exit For ElseIf child IsNot Nothing Then child = GetFrameworkElementByName(Of T)(child) If child IsNot Nothing AndAlso child.[GetType]() = GetType(T) Then Exit For End If End If Next Return TryCast(child, T) End FunctionEnd Class