2
votes

I am trying to write simple multi-filtering for datagrid. The concept is to add TextBox to each column header in data grid. User may type some value in each TextBox and then rows in DataGrid will be filtered. Columns are generated dynamiclly. I am doing this in code-behind. To add the TextBox to column header I have created new DataTemplate and assigned that to HeaderTemplate of column as below:

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);

Recent view of DataGrid column headers:

What is my problem. When I am setting TextBox HorizontalAlignment value to "Stretch" nothing happened. As you can see in the picture above columns have some specific width (which value is equal to Auto) but TextBox HorizontalAlignment remains with its default value.

My goal is to have this TextBoxes stretched even when user will resize a column (dragging left or right).

How to set TextBox value HorizontalAlignment to stretch? Where I am missing something? Does any additional binding or some other mechanism is necessary to obtain stretching when width of the column is changing?

1
It looks like your text box ends up in another container that has exactly that size. Stretch doesn't mean "Push" but rather "occupy what you can". If you snoop this you will find that it does indeed stretch.Rob

1 Answers

1
votes

Use a ColumnHeaderStyle that sets the HorizontalContentAlignment to true:

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

You could create the Style in the code-behind if you have to:

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;