我的XAML设计中有一个DataTemplate。
sixth_nnd
我这样称呼它:
<DataTemplate x:Key="dt1">
<StackPanel Orientation="Vertical" Height="388">
<RelativePanel>
<TextBlock x:Name="titleText" Text="{Binding Path=titleText}" Foreground="White" FontSize="40" TextLineBounds="TrimToCapHeight" Margin="0,6,0,0" />
</RelativePanel>
</StackPanel>
</DataTemplate>
然后,我使用下面的代码尝试在<ContentControl x:Name="r3" ContentTemplate="{StaticResource dt1}"/>
内找到titleText
。
DataTemplate
但是我失败了,日志在下面:
public object FindChildInDT<T>(T inputElement, string childName)
{
DataTemplate dt = (inputElement as ContentControl).ContentTemplate;
DependencyObject dio = dt.LoadContent();
foreach (var tb1 in FindVisualChildren<ContentControl>(dio))
{
if (tb1.Name == childName)
{
return tb1;
}
}
return null;
}
private static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
private void Grid_Loaded(object sender, RoutedEventArgs e)
{
TextBlock tts = FindChildInDT(r3, "titleText") as TextBlock;
if (tts == null)
Debug.WriteLine("tts is null");
else
Debug.WriteLine("tts is not null");
}