How to create a Custom Routed Event ? WPF c#

Jean Col picture Jean Col · Sep 5, 2013 · Viewed 9.3k times · Source

I followed this tutorial but I couldn't apply what I learned to my project.

I have a LineGraph object (Dynamic Data Display) and I want to create an event that is raised when the thickness of the LineGraph is equal to 0.

How am I supposed to write it following this tutorial ?

Answer

Ibrahim Najjar picture Ibrahim Najjar · Sep 5, 2013

Here is how I would do it with a RoutedEvent:

  1. Create a class that derives from LineGraph, let's say CustomLineGraph:

    public class CustomLineGraph : LineGraph {
    }
    
  2. Create our routed event like this:

    public class CustomLineGraph : LineGraph {
    
        public static readonly RoutedEvent ThicknessEvent = EventManager.RegisterRoutedEvent("Thickness", RoutingStrategy.Bubble, typeof(RoutedEventHandler, typeof(CustomLineGraph));
    
        // .NET event wrapper
        public event RoutedEventHandler Thickness
        {
            add { AddHandler(CustomLineGraph.ThicknessEvent, value); } 
            remove { RemoveHandler(CustomLineGraph.ThicknessEvent, value); }
        }
    }
    
  3. Now we override the StrokeThickness property so we can raise our custom routed event when the value of that property is 0.

    public class CustomLineGraph : LineGraph {
    
        public static readonly RoutedEvent ThicknessEvent = EventManager.RegisterRoutedEvent("Thickness", RoutingStrategy.Bubble, typeof(RoutedEventHandler, typeof(CustomLineGraph));
    
        // .NET event wrapper
        public event RoutedEventHandler Thickness
        {
            add { AddHandler(CustomLineGraph.ThicknessEvent, value); } 
            remove { RemoveHandler(CustomLineGraph.ThicknessEvent, value); }
        }
    
        public override double StrokeThickness {
            get { return base.StrokeThickness; }
            set
            {
                base.StrokeThickness = value;
                if (value == 0)
                    RaiseEvent(new RoutedEventArgs(CustomLineGraph.ThicknessEvent, this));
            }
        }
    }
    
  4. We are done !