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?