假设我有以下内容:
<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}" />
Run Code Online (Sandbox Code Playgroud)
现在假设Content正在绑定到 a 的新实例MainViewModel。通过 WPF 的魔力DataTemplates,它会创建一个UserControl MainBaseViewwhere 的实例ContentControl并将其DataContext设置为Binding。
问题是,你到底如何访问这个生成的内容(即MainBaseView实例)?我想绑定uxButtons'DataContext到生成的网格内Content,但在检查中Content只包含了结合,而不是MainBaseView实例及其逻辑/视频树。
/// <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;
}
Run Code Online (Sandbox Code Playgroud)
然后你只需调用
var baseView = uxMaster.GetChildOfType<MainBaseView>()
Run Code Online (Sandbox Code Playgroud)