数据网格行 Header 未根据内容调整大小

Data Grid Row Header Not Resizing To Contents

我正在自定义 DataGrid,以便用户可以通过文本框将信息直接输入 header。

我遇到的问题是,当文本更改时,header 行没有调整大小以匹配内容的大小:

之前:

之后:

如您所见,header 不会缩小文本框的大小以匹配文本框,一旦文本框的大小已缩小以匹配新文本。

符合Minimal, Complete and Verifiable Example要求:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:l="clr-namespace:MCVE"
    xmlns:lib="clr-namespace:System;assembly=mscorlib"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    x:Class="MCVE.MainWindow"
    mc:Ignorable="d" Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <x:Array x:Key="Source" Type="{x:Type lib:String}">
            <lib:String>Foo</lib:String>
            <lib:String>Bar</lib:String>
            <lib:String>Baz</lib:String>
        </x:Array>
    </Window.Resources>
    <DataGrid
        AutoGenerateColumns="False"
        ItemsSource="{StaticResource Source}"
        RowHeight="50">
        <DataGrid.RowHeaderStyle>
            <Style TargetType="{x:Type DataGridRowHeader}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate>
                            <TextBox FontSize="36" HorizontalAlignment="Left" Text="This Is A Test" />
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </DataGrid.RowHeaderStyle>
    </DataGrid>
</Window>

在任意行 header 中输入一些内容。然后清空重现。

那么我该怎么做才能强制行 header 宽度并确保它保持尽可能小的宽度(不侵占实际行 header 内容)?

您可以处理 TextBox 元素的 SizeChanged 事件并跟踪它们的宽度。试试这个:

private readonly Dictionary<TextBox, double> _widths = new Dictionary<TextBox, double>();
private void TextBox_SizeChanged(object sender, SizeChangedEventArgs e)
{
    TextBox textBox = (TextBox)sender;
    _widths[textBox] = textBox.ActualWidth;

    double largestWidth = _widths.Values.Max();
    DataGridRowHeader header = FindParent<DataGridRowHeader>(textBox);
    dg.RowHeaderWidth = double.NaN;
    if (header != null)
        dg.RowHeaderWidth = dg.RowHeaderActualWidth > largestWidth ? largestWidth : double.NaN;
}

XAML:

<DataGrid.RowHeaderStyle>
    <Style TargetType="{x:Type DataGridRowHeader}">
        <Setter Property="Width" Value="Auto" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <TextBox FontSize="36" HorizontalAlignment="Left" Text="This Is A Test"
                                           SizeChanged="TextBox_SizeChanged" />
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</DataGrid.RowHeaderStyle>