title: Using code behind only add button to dynamically generated WPF DataGrid column's header
body: <p>I have a wpf datagrid that has it's columns generated dynamically in code and I need to insert small buttons in each column's header to the right of the text to implement custom (complex) filtering in a popup dialog.</p>
  
  <p>I'm having trouble figuring out how to insert a button into a datagrid column header using only code behind.</p>
  
  <p>This is the route I started going down (commented out bit) but it doesn't work:</p>
  
  <pre><code>private static DataGridTextColumn GetTextColumn(string ColumnName, string FormatString, bool AlignRight)
         {
             DataGridTextColumn c = new DataGridTextColumn();
             c.Header = Test.Common.UIBizObjectCache.LocalizedText.GetLocalizedText(ColumnName);
             c.Binding = new System.Windows.Data.Binding(ColumnName);
             if (!string.IsNullOrWhiteSpace(FormatString))
                 c.Binding.StringFormat = FormatString;
             if (AlignRight)
             {
                 Style cellRightAlignedStyle = new Style(typeof(DataGridCell));
                 cellRightAlignedStyle.Setters.Add(new Setter(DataGridCell.HorizontalAlignmentProperty, HorizontalAlignment.Right));
                 c.CellStyle = cellRightAlignedStyle;
             }
  
             //var buttonTemplate = new FrameworkElementFactory(typeof(Button));
             //buttonTemplate.Text = "X";
             //buttonTemplate.AddHandler(
             //                   Button.ClickEvent,
             //                   new RoutedEventHandler((o, e) =&gt; HandleColumnHeaderButtonClick(o, e))
             //               );
             //c.HeaderTemplate=new DataTemplate(){VisualTree = buttonTemplate};
  
             return c;
         }
  </code></pre>
  
  <p>I get an invalidoperationexception "'ContentPresenter' type must implement IAddChild to be used in FrameworkElementFactory AppendChild."</p>
  
  <p>Clearly I'm doing it wrong. :) Any help would be greatly appreciated.</p>