Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you access the DataTemplate generated content of a databound ContentControl?

Tags:

c#

wpf

xaml

Let's say I have the following:

<FrameworkElement.Resources>
    <DataTemplate DataType="{x:Type viewmodel:MainViewModel}">
        <view:MainBaseView />
    </DataTemplate>
</FrameworkElement.Resources>

<ContentControl x:Name="uxMaster" Grid.Row="0" Content="{Binding}" />
<view:AddRemoveBaseView x:Name="uxButtons" Grid.Row="1"
      DataContext="{Binding ElementName=uxMaster, Path=Content.uxGrid}" />

Now let's say that the Content is binding to a new instance of a MainViewModel. Through the magic of WPF DataTemplates, it will create an instance of the UserControl MainBaseView where the ContentControl is and set its DataContext to the Binding.

Question is, how the heck do you access this generated content (i.e. the MainBaseView instance)? I'm trying to bind uxButtons' DataContext to a grid inside of the generated Content, but upon inspecting the Content it only contains the binding and not the MainBaseView instance and its logical/visual tree.

like image 374
Anthony Avatar asked Oct 06 '22 05:10

Anthony


1 Answers

/// <summary>
/// Get the first child of type T in the visual tree.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>the first child of type T in the visual tree, or null if no such element exists</returns>
public static T GetChildOfType<T>(this DependencyObject source) where T : DependencyObject
{
    for (var i = 0; i < VisualTreeHelper.GetChildrenCount(source); i++)
    {
        var child = VisualTreeHelper.GetChild(source, i);
        if (child != null && child.GetType() == typeof(T))
            return child as T;
    }

    for (var i = 0; i < VisualTreeHelper.GetChildrenCount(source); i++)
    {
        var child = VisualTreeHelper.GetChild(source, i);
        var t = child.GetChildOfType<T>();
        if (t != null) return t;
    }

    return null;
}

then you simply call

var baseView = uxMaster.GetChildOfType<MainBaseView>()
like image 146
Dtex Avatar answered Oct 10 '22 03:10

Dtex