如何在代码隐藏列标题中为TextBox设置拉伸?

时间:2018-11-09 11:50:30

标签: c# wpf wpf-controls code-behind

我正在尝试为datagrid编写简单的多重过滤。概念是将TextBox添加到数据网格中的每个列标题。用户可以在每个TextBox中键入一些值,然后将过滤DataGrid中的行。 列是动态生成的。我在后台代码中执行此操作。 要将TextBox添加到列标题中,我创建了新的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列标题的最新视图:

我怎么了?当我将TextBox Horizo​​ntalAlignment值设置为“ Stretch”时,没有任何反应。如上图所示,列具有特定的宽度(该值等于“自动”),但TextBox Horizo​​ntalAlignment保留其默认值。

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

如何设置TextBox值Horizo​​ntalAlignment进行拉伸?我在哪里想念什么?更改列宽时,是否需要任何其他绑定或某种其他机制来获得拉伸?

1 个答案:

答案 0 :(得分:0)

使用将ColumnHeaderStyle设置为HorizontalContentAlignment的{​​{1}}:

true

如果需要,您可以在后面的代码中创建<DataGrid x:Name="dataGrid"> <DataGrid.ColumnHeaderStyle> <Style TargetType="{x:Type DataGridColumnHeader}"> <Setter Property="HorizontalContentAlignment" Value="Stretch" /> </Style> </DataGrid.ColumnHeaderStyle> </DataGrid>

Style