#606 – Reusing an Existing Routed Event in Your Class

When you are defining a new CLR event in a class that will wrap a routed event, you can either register your own new routed event or you can reuse a routed event that already exists in the WPF framework.

To reuse an existing routed event, you call the AddOwner method on the existing event.

    public class MyButton : Button
    {
        public static readonly RoutedEvent MyTextChangedEvent;

        static MyButton()
        {
            MyTextChangedEvent = TextBoxBase.TextChangedEvent.AddOwner(typeof(MyButton));
        }

        public event TextChangedEventHandler MyTextChanged
        {
            add { AddHandler(MyTextChangedEvent, value); }
            remove { RemoveHandler(MyTextChangedEvent, value); }
        }

        protected virtual void OnMyTextChanged()
        {
            TextChangedEventArgs evargs = new TextChangedEventArgs(MyTextChangedEvent, UndoAction.None);
            RaiseEvent(evargs);
        }

        public MyButton()
        {
            this.Click += new RoutedEventHandler(MyButton_Click);
        }

        void MyButton_Click(object sender, RoutedEventArgs e)
        {
            this.Content = this.Content + ".";
            OnMyTextChanged();
        }
    }

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

One Response to #606 – Reusing an Existing Routed Event in Your Class

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

Leave a comment