如何更改位于HeaderTemplate内的DataTemplate内的TextBlock文本

时间:2013-09-27 07:33:56

标签: wpf datagrid

<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的文本

1 个答案:

答案 0 :(得分: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);
        }
    }