1

I use add[EventName]handler method to add a reference of the dependecy object to a singleton. In the following example there's a simple console output to demonstrate the problem.

public class Included
{
    public static readonly RoutedEvent DummyEvent = EventManager.RegisterRoutedEvent("Included.DummyEvent", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(Included));

    public static void AddDummyHandler(DependencyObject d, RoutedEventHandler handler)
    {
        Console.WriteLine("-------------- included project dummy event handler");
        UIElement element = d as UIElement;

        if (element != null)
        {
            element.AddHandler(DummyEvent, handler);
        }
    }

    public static void RemoveDummyHandler(DependencyObject d, RoutedEventHandler handler)
    {
        UIElement element = d as UIElement;
        if (element != null)
        {
            element.RemoveHandler(DummyEvent, handler);
        }
    }
}

This works when I include this class in to the project that I want to use. I use the attached event in the xaml like:

<Button Name="MyButton" Width="200" Height="30" local:Included.Dummy="IncludedProject">IncludedToProject</Button>

Which writes "-------------- included project dummy event handler" to the console when i run the app.

The problem is when I use the same code in a class library, xaml doesn't trigger AddDummyHandler.

public class ExcludedClassLibrary
{

    public static readonly RoutedEvent DummyEvent = EventManager.RegisterRoutedEvent("Excluded.DummyEvent", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ExcludedClassLibrary));

    public static void AddDummyHandler(DependencyObject d, RoutedEventHandler handler)
    {
        Console.WriteLine("-------------- excluded project dummy event handler");
        UIElement element = d as UIElement;

        if (element != null)
        {
            element.AddHandler(DummyEvent, handler);
        }
    }

    public static void RemoveDummyHandler(DependencyObject d, RoutedEventHandler handler)
    {
        UIElement element = d as UIElement;
        if (element != null)
        {
            element.RemoveHandler(DummyEvent, handler);
        }
    }

}

You can download and test the sample project

emrah ozer
  • 11
  • 1
  • 2

0 Answers0