如何访问DataTemplate生成的数据绑定ContentControl内容?

时间:2012-10-23 21:33:35

标签: c# wpf

假设我有以下内容:

<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}" />

现在让我们说Content绑定到MainViewModel的新实例。通过WPF DataTemplates的魔力,它将创建ContentControl所在的UserControl MainBaseView实例,并将其DataContext设置为Binding。

问题是,你如何访问这个生成的内容(即MainBaseView实例)?我正在尝试将uxButtons的DataContext绑定到生成内容中的网格,但在检查内容时,它只包含绑定,而不包含MainBaseView实例及其逻辑/可视树。

1 个答案:

答案 0 :(得分:3)

/// <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;
}

然后你只需致电

var baseView = uxMaster.GetChildOfType<MainBaseView>()