Inheritance of Attached Behaviors

I would like to implement a set of similar applied actions for use in a WPF application. Since they all share a piece of template code that I really don't want to repeat for everyone, I would like to create a basic behavior inherited from it. But since everything inside the attached behavior is static, I don’t understand how to do it.

As an example, take this behavior that the method executes in mousedown (the real behavior, of course, will do something that is not easy to do in the event handler):

public static class StupidBehavior { public static bool GetIsEnabled(DependencyObject obj) { return (bool)obj.GetValue(IsEnabledProperty); } public static void SetIsEnabled(DependencyObject obj, bool value) { obj.SetValue(IsEnabledProperty, value); } // Using a DependencyProperty as the backing store for ChangeTooltip. This enables animation, styling, binding, etc... public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached("IsEnabled", typeof(bool), typeof(StupidBehavior), new UIPropertyMetadata(false, IsEnabledChanged)); private static void IsEnabledChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) { ((UIElement)sender).MouseDown += { (o,e) => MyMethod(); }; } private static void MyMethod() { MessageBox.Show("Boo"); } } 

Now I would like to create a new behavior, which should have a different implementation of MyMethod, as well as some additional properties that control it. How to do it?

+4
source share
2 answers

You can create another attached property that contains a detailed implementation that is invoked by the main behavior as a replacement for the subclass. An object that has a property can be non-static and used as a state-object .

(Perhaps you can put this in one property, and property == null means off)

+2
source

You can use the static constructor to compile a Dictionary<DependencyProperty,EventHandler> to map a specific DP to a specific handler and use the general DependencyPropertyChanged callback:

 static StupidBehavior() { handlerDictionary[IsEnabledProperty] = (o,e) => MyMethod(); handlerDictionary[SomeOtherProperty] = (o,e) => SomeOtherMethod(); } private static void CommonPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) { var uie = sender as UIElement; if (uie != null) { //removing before possibly adding makes sure the multicast delegate only has 1 instance of this delegate sender.MouseDown -= handlerDictionary[args.Property]; if (args.NewValue != null) { sender.MouseDown += handlerDictionary[args.Property]; } } } 

Or just do a switch on args.Property . Or something in between that includes a generic method and branching based on DependencyProperty .

And I'm not sure why your IsEnabled property is dealing with a value of type DependencyProperty , and not with something that would make a more meaningful feeling like bool .

+1
source

All Articles