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.
/// <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>()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With