我正在尝试为数据网格编写简单的多重过滤。这个概念是将 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 列标题的最新 View :
我的问题是什么。当我将 TextBox HorizontalAlignment 值设置为“Stretch”时,没有任何反应。正如您在上图中看到的那样,列有一些特定的宽度(该值等于 Auto),但 TextBox HorizontalAlignment 保持其默认值。
我的目标是即使在用户调整列大小时(向左或向右拖动)也能拉伸(stretch)此 TextBoxes。
如何设置TextBox值HorizontalAlignment为stretch?我在哪里遗漏了什么?当列的宽度发生变化时,是否需要任何额外的绑定(bind)或其他一些机制来获得拉伸(stretch)?
最佳答案
使用 ColumnHeaderStyle
将 HorizontalContentAlignment
设置为 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;
关于c# - 如何在代码隐藏的列标题中为 TextBox 设置拉伸(stretch)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53225209/