0
<wpf:DataGridTemplateColumn.HeaderTemplate >
   <DataTemplate>
      <TextBlock Text="PQR" TextWrapping="Wrap" Width="100" Name="ABC" TextAlignment="Center" Text="PQR" FontWeight="Bold"   HorizontalAlignment="Center"  VerticalAlignment="Center"/>
   </DataTemplate>
</wpf:DataGridTemplateColumn.HeaderTemplate>

现在我需要在运行时更改 ABC TextBlock 的文本

4

1 回答 1

0

这些代码对我有用:

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);
        }
    }
于 2013-09-27T08:43:10.100 回答