本文介绍了DataGridColumnHeader ContextMenu以编程方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在View.cs中有这个代码

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?

推荐答案

你只需要检索并设置其ContextMenu。

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;
}

这里是SafeFindDescendant扩展方法:

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;
    }
}

这篇关于DataGridColumnHeader ContextMenu以编程方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 20:29