2012-12-06 14 views
7

Mam ten kod w View.csDataGridColumnHeader ContextMenu programowo

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

this.DataGridAllJobs.ContextMenu = contextMenu; 

Ale chcę dodać do tego menu kontekstowe tylko cel. Czy to możliwe?

Odpowiedz

7

Musisz tylko pobrać DataGridColumnHeadersPresenter swojej DataGrid i ustawić jej 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; 
} 

A oto SafeFindDescendant metodę rozszerzenia:

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

I thnink wygrasz to 50 punktów reputacji. Moje tak ciężko zarobione 50 punktów ..) Dlaczego czekałeś, aż opublikuję go z nagrodą? =) Thx za odpowiedź!) – MikroDel

+1

Niestety nie widziałem tego wcześniej :) Próbuję odpowiedzieć na jak najwięcej pytań WPF, ale nie mogę odpowiedzieć na wszystkie pytania. Jednak zawsze patrzę na nagrody :) Nie zapomnij oznaczyć jako odpowiedź, jeśli to rozwiązało Twój problem! – Sisyphe

+0

Podniosłem pytanie, ponieważ było to interesujące. To będzie 10rep mniej stracone dla twojej nagrody;) – Sisyphe

Powiązane problemy