#604 – Defining a New Routed Event

You can create a new routed event in your own class, typically in a control.  Here, we define a new event named RightDrag in the MyButton class, which derives from Button.

Define a static object of type RoutedEvent.

public static readonly RoutedEvent RightDragEvent;

In the static constructor, register the event and set the RoutedEvent object.

        static MyButton()
        {
            RightDragEvent = EventManager.RegisterRoutedEvent("RightDrag", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyButton));
        }

Define a CLR event of type RoutedEventHandler or one of its subtypes.  Call the AddHandler/RemoveHandler methods.

        public event RoutedEventHandler RightDrag
        {
            add { AddHandler(RightDragEvent, value); }
            remove { RemoveHandler(RightDragEvent, value); }
        }

Add a helper method to fire the event.

        protected virtual void OnRightDrag()
        {
            RoutedEventArgs evargs = new RoutedEventArgs(RightDragEvent, this);
            RaiseEvent(evargs);
        }

Finally, fire your event when appropriate.

        void MyButton_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (e.RightButton == MouseButtonState.Pressed)
                OnRightDrag();
        }
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #604 – Defining a New Routed Event

  1. Pingback: Dew Drop – July 17, 2012 (#1,365) | Alvin Ashcraft's Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: