gpt4 book ai didi

wpf - 以编程方式 DataGridColumnHeader ContextMenu

转载 作者:行者123 更新时间:2023-12-04 11:40:47 24 4
gpt4 key购买 nike

我在 View.cs 中有这段代码

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

this.DataGridAllJobs.ContextMenu = contextMenu;

但我只想为标题添加这个上下文菜单。是否可以?

最佳答案

您只需要检索 DataGridColumnHeadersPresenter的 DataGrid 并设置其 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 扩展方法:
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;
}
}

关于wpf - 以编程方式 DataGridColumnHeader ContextMenu,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13746689/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com