Create and apply style from code-behind

Jan 16, 2009 at 6:48 AM
Hi,

I am trying to create a context menu for the datagrid header columns. This is being done using an attached property. Single-step trough the code below proves that the style is created, and assigned to the HeaderStyle property on every column. But the style is not applied.

So my question is, what am I doing wrong? :-)

    public class DataGridHeaderContextMenu : ContextMenu
{
#region AutoGenerateProperty
public static readonly DependencyProperty AutoGenerateProperty = DependencyProperty.RegisterAttached("AutoGenerate", typeof(bool), typeof(DataGridHeaderContextMenu), new PropertyMetadata(false, new PropertyChangedCallback(autoGenerate_Changed)));

public static void SetAutoGenerate(UIElement element, Boolean value)
{
element.SetValue(AutoGenerateProperty, value);
}

public static Boolean GetAutoGenerate(UIElement element)
{
return (Boolean)element.GetValue(AutoGenerateProperty);
}

static void autoGenerate_Changed(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
if (obj is Microsoft.Windows.Controls.DataGrid)
{
if ((bool)e.NewValue)
{
DataGrid grid = (DataGrid)obj;

DataGridHeaderContextMenu menu = new DataGridHeaderContextMenu(grid);

Style style = new Style(typeof(DataGridColumnHeader));
style.Setters.Add(new Setter(DataGridColumnHeader.ContextMenuProperty, menu));

foreach (DataGridColumn column in grid.Columns)
{
column.HeaderStyle = style;
}
}
}
else
{
Trace.WriteLine("DataGridHeaderContextMenu: Only 'Microsoft.Windows.Controls.DataGrid' is supported.");
}
}
#endregion

public DataGridHeaderContextMenu(DataGrid grid)
{
Items.Add("Header dummy menu");
}
}
Jan 16, 2009 at 6:57 AM
Instead of:
                    foreach (DataGridColumn column in grid.Columns)
{
column.HeaderStyle = style;
}
Use:
                    grid.ColumnHeaderStyle = style;
And it works :-)