5

假设我有以下内容:

<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绑定到 a 的新实例MainViewModel。通过 WPF 的魔力DataTemplates,它将创建一个UserControl MainBaseViewwhere ContentControlis 的实例并将其设置DataContextBinding.

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

4

1 回答 1

4
/// <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>()
于 2012-10-24T07:11:07.627 回答