WPF: Programatically adding a ContextMenu to a DataGrid column header

1.6k views Asked by At

I'm trying to add individualized and separate ContextMenus to each column header in my project, so that when a user right-clicks a header, a menu of checkboxes that relates to that header will appear that allows them to filter the data.

A couple of catches: the project that I'm working on needs to be developed for .NET 4.0, and as such I don't have access to the DataGridColumnHeader class that was introduced in .NET 4.5. Also, all of this needs to be done programatically, no XML allowed, as all of the column data is determined at runtime.

I found a similar Stack question in which this is done using XML, and I've sucessfully reproduced it in XML, but I'm new to WPF and haven't been able to reproduce it programatically.

I've pasted some C# code below where I think the setup should occur.

    /// <summary>
    /// Function that adds all of the columns for the default setup
    /// </summary>
    public void MakeAllColumns()
    {
        for (int i = 0; i < AllColumnDisplayNames.Length; i++)
        {
            DataGridTextColumn col = new DataGridTextColumn();
            col.Header = AllColumnDisplayNames[i];
            col.Binding = new Binding(AllColumnBindings[i]);
            canGrid.Columns.Add(col);

            // code for addding context menus will most likely go here


        }
    }
1

There are 1 answers

1
MisterXero On BEST ANSWER

DataGridColumns are not FrameworkElements so they do not have a ContextMenu. Since you want to do this all in code behind specifying a data template for the column can be a pain (IMHO). You could try passing in a FrameworkElement as the Header object for the column and set the context menu on that framework element.

Example:

//...

    DataGridTextColumn col = new DataGridTextColumn();

    //...

    TextBlock txt = new TextBlock() { Text = AllColumnDisplayNames[i] };
    txt.ContextMenu = new ContextMenu(); // Build your context menu here.

    col.Header = txt;

    //...