如何设置 code-behind 中 header 列的 TextBox 的拉伸?

How to set stretching for TextBox in column header in code-behind?

我正在尝试为数据网格编写简单的 multi-filtering。这个概念是将 TextBox 添加到数据网格中的每一列 header。用户可以在每个 TextBox 中键入一些值,然后 DataGrid 中的行将被过滤。 列是动态生成的。我在 code-behind 中这样做。 要将 TextBox 添加到列 header,我创建了新的 DataTemplate 并将其分配给列的 HeaderTemplate,如下所示:

DataGridTextColumn column = new DataGridTextColumn();

FrameworkElementFactory textBox = new FrameworkElementFactory(typeof(TextBox));
textBox.SetValue(NameProperty, "exemplaryName");
textBox.SetValue(HorizontalAlignmentProperty, HorizontalAlignment.Stretch);

FrameworkElementFactory textBlock = new FrameworkElementFactory(typeof(TextBlock));
textBlock.SetValue(TextBlock.TextProperty, "exemplaryName");

FrameworkElementFactory stackPanel = new FrameworkElementFactory(typeof(StackPanel));

stackPanel.AppendChild(textBox);
stackPanel.AppendChild(textBlock);

DataTemplate headerTemplate = new DataTemplate();       
headerTemplate.VisualTree = stackPanel;
column.HeaderTemplate = headerTemplate;

temp.dataGrid.Columns.Add(column);

最近查看 DataGrid 列 headers:

我的问题是什么。当我将 TextBox Horizo​​ntalAlignment 值设置为 "Stretch" 时,没有任何反应。正如您在上图中看到的那样,列有一些特定的宽度(该值等于 Auto),但 TextBox Horizo​​ntalAlignment 保持其默认值。

我的目标是即使在用户调整列大小时(向左或向右拖动)也能拉伸此文本框。

如何设置TextBox值Horizo​​ntalAlignment为拉伸?我在哪里遗漏了什么?当列的宽度发生变化时,是否需要任何额外的绑定或其他一些机制来获得拉伸?

使用 ColumnHeaderStyleHorizontalContentAlignment 设置为 true:

<DataGrid x:Name="dataGrid">
    <DataGrid.ColumnHeaderStyle>
        <Style TargetType="{x:Type DataGridColumnHeader}">
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
        </Style>
    </DataGrid.ColumnHeaderStyle>
</DataGrid>

如果必须,您可以在代码隐藏中创建 Style

const string Xaml = "<Style xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" TargetType=\"{x:Type DataGridColumnHeader}\"><Setter Property=\"HorizontalContentAlignment\" Value=\"Stretch\" /></Style>";
temp.dataGrid.ColumnHeaderStyle = XamlReader.Parse(Xaml) as Style;