Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridColumnHeader ContextMenu programmatically

I have this code in View.cs

var contextMenu = this.dataGridFacade.GiveContextMenuForDataGrid(this.DataGridAllJobs);

this.DataGridAllJobs.ContextMenu = contextMenu;

But I want to add this context menu for header only. Is it possible?

like image 867
MikroDel Avatar asked Dec 06 '12 15:12

MikroDel


1 Answers

You just have to retrieve the DataGridColumnHeadersPresenter of your DataGrid and set its ContextMenu.

var contextMenu = this.dataGridFacade.GiveContextMenuForDataGrid(this.DataGridAllJobs);
var columnHeadersPresenter = this.DataGridAllJobs.SafeFindDescendant<DataGridColumnHeadersPresenter>(ip => ip.Name == "PART_ColumnHeadersPresenter");
if (columnHeadersPresenter != null)
{
    columnHeadersPresenter.ContextMenu = contextMenu;
}

And here is the SafeFindDescendant extension method :

public static class Visual_ExtensionMethods
{
    /// <summary>
    /// Retrieves the first Descendant of the currren Visual in the VisualTree matching the given predicate
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="this">The current Visual.</param>
    /// <param name="predicate">An optional predicate that the descendant have to satisfy.</param>
    /// <returns></returns>
    public static T SafeFindDescendant<T>(this Visual @this, Predicate<T> predicate = null) where T : Visual
    {
        T result = null;
        if (@this == null)
        {
            return null;
        }

        // iterate on VisualTree children thanks to VisualTreeHelper
        int childrenCount = VisualTreeHelper.GetChildrenCount(@this);
        for (int i = 0; i < childrenCount; i++)
        {
            var currentChild = VisualTreeHelper.GetChild(@this, i);

            var typedChild = currentChild as T;
            if (typedChild == null)
            {
                // recursive search
                result = ((Visual)currentChild).SafeFindDescendant<T>(predicate);
                if (result != null)
                {
                    break;
                }
            }
            else
            {
                if (predicate == null || predicate(typedChild))
                {
                    result = typedChild;
                    break;
                }
            }
        }

        return result;
    }
}
like image 188
Sisyphe Avatar answered Oct 21 '22 07:10

Sisyphe