tags:

views:

29

answers:

2

How can I define one global GridViewColumnHeader.Click handler for any ListView.GridViewColumnHeader in my project?

I mean is it possible to set a Style or a Template in app.xaml for TargetType=GridViewColumnHeader so any columnheader in any listview in the project would response to the method in app.xaml.cs?

+1  A: 

Though it isn't a global event handler, I would simply create a new control that inherits from ListView and implement the Click handler there.

Austin Salonen
+1  A: 

Yes, with one caveat: You can create a Style that applies to all GridViewColumnHeaders, but you cannot set the Click event in it. However you can set the Command property which has almost exactly the same result:

<Application.Resources>
  <Style TargetType="GridViewColumnHeader">
    <Setter Property="Command"
            Value="{x:Static local:GridViewClickHandler.ClickCommand}" />
  </Style>
  ...

Now it is only required to create the command, register a class handler, and write the code to handle it:

public GridViewClickHandler
{
  public RoutedCommand ClickCommand;

  static GridViewClickHandler()
  {
    ClickCommand = new RoutedCommand("ClickCommand", typeof(GridViewClickHandler));
    CommandManager.RegisterClassCommandBinding(
      typeof(GridViewColumnHeader),
      new CommandBinding(ClickCommand, OnColumnHeaderClick));
  }

  static void OnColumnHeaderClick(object sender, ExecutedRoutedEventArgs e)
  {
    // your code here
  }
}

Note that if you manually set the GridViewColumnHeader's Command property anywhere else in your application it will take precedence over the style. If this is a concern, you may want to instead catch tunneling PreviewMouseDown events at your Window and check each to see if it's original source is a GridViewColumnHeader.

Ray Burns