2012-12-06 18 views
7

我有这样的代码在View.csDataGridColumnHeader文本菜单编程

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

this.DataGridAllJobs.ContextMenu = contextMenu; 

但我想添加这个上下文菜单中只有头。可能吗?

回答

7

您只需检索DataGrid的DataGridColumnHeadersPresenter并设置其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; 
    } 
} 
+0

我thnink你赢了50点声望。我很难得到50分..)为什么你等到我发布奖励? =)Thx为你回答! ) – MikroDel

+1

对不起,我没有看到这个更快:)我尝试回答尽可能多的WPF问题,但不能全部回答。不过,我总是看看赏金:)不要忘记标记为答案,如果它解决了你的问题! – Sisyphe

+0

由于间歇性而加大了您的问题。这将是10rep损失为您的赏金;) – Sisyphe