"Global" event handler

I've searched for a long time and cannot find the answer to this question. It might just be a matter of not knowing what to search for. Is it possible to have a "global" handler available for FrameworkElements?

For example:

On Page 1

<Grid x:Name="Grid1" Unloaded="GlobalHandler"/>

On Page 2

<Grid x:Name="Grid2" Unloaded="GlobalHandler"/>

Global handler? Where can I store this code so it's available for both Grids?

private void GlobalHandler(object sender, RoutedEventArgs e)
{
    //Do something with grid here
}

Answers


Create a static method with the same signature, then in your page, call the static method from your individual handlers.

public class EventHandlerHelper
{
  public static GlobalUnload(object sender, RoutedEventArgs e)
  {
    // work
  }
}

public class Page1
{
   public void GlobalHandler(object sender, RoutedEventArgs e)
   {
      EventHandlerHelper.GlobalUnload(sender, e);
   }
}

public class Page2
{
   public void GlobalHandler(object sender, RoutedEventArgs e)
   {
      EventHandlerHelper.GlobalUnload(sender, e);
   }
}

If you want to stick a little more to XAML you can declare an EventSetter for a style in a ResourceDictionary and merge said dictionary into which ever Pages require it.

Straight from this MSDN forum thread thanks to user Kevin Pan

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    x:Class="MyResource.MyResourceDictionary"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="Grid" x:Key="mycanvasstyle">
    <EventSetter Event="Unloaded"Handler="MyResourceDictionary_GlobalHandler"/>
    </Style>
</ResourceDictionary>

In the partial class for the ResourceDictionary

void MyResourceDictionary_GlobalHandler(object sender, MouseButtonEventArgs e)
{
    //Do something with grid here
}

And then add this to each Pages' XAML

<Page>
    <Page.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Dictionary1.xaml"></ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Page.Resources>

    <!-- rest of page -->

</Page>

Need Your Help

how to hide navigationbar when i push from navigation controller?

iphone objective-c uinavigationcontroller uinavigationbar

how to hide top bar in UIViewcontroller when i push from navigation controller using

Method for storing a large amount of units, with a large array of attributes

java database-design game-engine

Me and a friend are currently looking at developing a game, with similarities to a certain trademarked francise. To define the units in the game, we've created an abstract class which denotes the 44