开发者

Global event handler

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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜