C# 如何访问数据绑定ContentControl的DataTemplate生成的内容?
假设我有以下几点:C# 如何访问数据绑定ContentControl的DataTemplate生成的内容?,c#,wpf,xaml,C#,Wpf,Xaml,假设我有以下几点: <FrameworkElement.Resources> <DataTemplate DataType="{x:Type viewmodel:MainViewModel}"> <view:MainBaseView /> </DataTemplate> </FrameworkElement.Resources> <ContentControl x:Name="uxMaster"
<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}" />
现在让我们假设内容
绑定到MainViewModel
的新实例。通过WPFDataTemplates
的魔力,它将在ContentControl
所在的位置创建一个UserControl
MainBaseView
实例,并将其DataContext
设置为绑定
问题是,如何访问生成的内容(即MainBaseView
实例)?我试图将uxButtons的DataContext
绑定到生成的内容的网格中,但在检查内容时,它只包含绑定,而不包含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;
}
///获取可视化树中T类型的第一个子级。
///
///
///可视树中T类型的第一个子元素,如果不存在此类元素,则为null
公共静态T GetChildOfType(此DependencyObject源),其中T:DependencyObject
{
for(变量i=0;i
然后你只要打个电话
var baseView = uxMaster.GetChildOfType<MainBaseView>()
var baseView=uxMaster.GetChildOfType()
你说的“包含xaml”是什么意思?您想要实际的标记文本作为绑定的结果,还是想要uxMaster内容的uxGrid
属性?对不起,我不是指xaml。。。我指的是包含uxGrid的元素树。换句话说,MainBaseView实例在哪里,这样我就可以遍历它的逻辑和可视树,并在需要时绑定到它?如果xaml与您提供的一样,您就不能键入{Binding uxGrid}
?否。如果{Binding}绑定到MainViewModel的实例,那么{Binding uxGrid}显然不起作用。MainViewModel没有uxGrid属性,但是由MainBaseView生成的DataTemplate有;我希望有人也能展示在纯xaml中是否可行(这种方法需要使用转换器)。