1

I have a ComboBox in a header of a DataGrid column. I want to handle the SelectionChanged event of the ComboBox but I need to know which control (in header of which column) generated that event. The controls are put in the headers through static resource DataTemplate assigned to HeaderTemplate in a call to column constructor.

I wanted to use the column data context to set some identifying data on the ComboBox but I can't access that context. I could easily access the DataGrid data model context but it is the same data for all ComboBoxes (columns).

Any idea how can I resolve which column header ComboBox generated the event?

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
bor
  • 658
  • 7
  • 19

1 Answers1

1

"which column header ComboBox generated the event?" (ComboBox)sender is your handle to the ComboBox that generated the event.

If you need to access the header, or the column containing that ComboBox, you can use the VisualTreeHelper, as discussed here: How can I find WPF controls by name or type?

Based on the information in your question, this answer from that thread might be what you are looking for (by John Myczek) - sub out Window for the type you want:

You can use the VisualTreeHelper to find controls. Below is a method that uses the VisualTreeHelper to find a parent control of a specified type. You can use the VisualTreeHelper to find controls in other ways as well.

public static class UIHelper
{
   /// <summary>
   /// Finds a parent of a given item on the visual tree.
   /// </summary>
   /// <typeparam name="T">The type of the queried item.</typeparam>
   /// <param name="child">A direct or indirect child of the queried item.</param>
   /// <returns>The first parent item that matches the submitted type parameter. 
   /// If not matching item can be found, a null reference is being returned.</returns>
   public static T FindVisualParent<T>(DependencyObject child)
     where T : DependencyObject
   {
      // get parent item
      DependencyObject parentObject = VisualTreeHelper.GetParent(child);

      // we’ve reached the end of the tree
      if (parentObject == null) return null;

      // check if the parent matches the type we’re looking for
      T parent = parentObject as T;
      if (parent != null)
      {
         return parent;
      }
      else
      {
         // use recursion to proceed with next level
         return FindVisualParent<T>(parentObject);
      }
   }
}

Call it like this:

Window owner = UIHelper.FindVisualParent<Window>(myControl);
Community
  • 1
  • 1
Bobby
  • 467
  • 4
  • 13
  • Thanks. Somehow I didn't think about walking up the visual tree... I so wanted to get the reference to the column in the event handler that I couldn't see the forest for the trees. Now I can find the header (instead of the column) and I can use the information from the header's tag property to process the event. – bor Jul 14 '15 at 07:07