这些代码对我有用:
在XAML中:
<DataGrid x:Name="parentObject">
<DataGrid.Columns>
<DataGridTemplateColumn IsReadOnly="True">
<DataGridTemplateColumn.HeaderTemplate>
<DataTemplate>
<TextBlock Text="PQR" TextWrapping="Wrap" Width="100" Name="ABC" TextAlignment="Center"
FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
在后面的代码中:
var textBlock = FindTextBlockName<TextBlock>("ABC", parentObject);
if (textBlock != null)
{
textBlock.Text = "NewText";
}
还要为方法编写这些代码FindTextBlockName
:
public static T FindTextBlockName<T>(string name, DependencyObject reference) where T : FrameworkElement
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentNullException("name");
}
if (reference == null)
{
throw new ArgumentNullException("reference");
}
return FindTextBlockNameInternal<T>(name, reference);
}
public static T FindTextBlockNameInternal<T>(string name, DependencyObject reference) where T : FrameworkElement
{
foreach (DependencyObject obj in GetChildren(reference))
{
T elem = obj as T;
if (elem != null && elem.Name == name)
{
return elem;
}
elem = FindTextBlockNameInternal<T>(name, obj);
if (elem != null)
{
return elem;
}
else
{
if (obj.GetType().FullName == "System.Windows.Controls.TextBlock")
elem = (obj as System.Windows.Controls.TextBlock) as T;
if (elem != null && elem.Name == name)
return elem;
}
}
return null;
}
private static IEnumerable<DependencyObject> GetChildren(DependencyObject reference)
{
int childCount = 0;
try
{
childCount = VisualTreeHelper.GetChildrenCount(reference);
}
catch (Exception sw)
{
}
for (int i = 0; i < childCount; i++)
{
yield return VisualTreeHelper.GetChild(reference, i);
}
}