#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();
        }
    }
Advertisements

#154 – Reusing an Existing Dependency Property in Your Class

We saw earlier how to register a new dependency property in a custom class using the DependencyProperty.Register method.  You can also reuse an existing dependency property, using the DependencyProperty.AddOwner method.

When you reuse an existing dependency property, you can optionally specify new metadata that applies to the use of the dependency property in your new type.  You should also define CLR properties in the new type that wrap the GetValue/SetValue calls to read/write dependency property values.

Here’s an example, where we reuse the BirthYearProperty, originally defined in a Person class, in a new Dog class.  Notice that we also provide a new default value.

        // Dog also has a BirthYear property
        public static readonly DependencyProperty BirthYearProperty =
            Person.BirthYearProperty.AddOwner(
                typeof(Dog),
                new PropertyMetadata(2000, new PropertyChangedCallback(OnBirthYearChanged)));

        public int BirthYear
        {
            get { return (int)GetValue(BirthYearProperty); }
            set { SetValue(BirthYearProperty, value); }
        }

        public static void OnBirthYearChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
        }