2011-05-10 42 views
4

我想要实现一组类似的附加行为以用于WPF应用程序。 因为他们都共享大量的样板代码,我不想重复每一个代码,我想创建一个从它继承的基本行为。 但是,由于附加行为中的所有内容都是静态的,所以我不知道如何去做。附加行为的继承

举例来说,采取这种行为,执行上的mousedown的方法(真正的行为当然会做一些不容易在一个事件处理完成):

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"); 
    }  
} 

现在,我想创建一种新的行为,应该有一个不同的MyMethod实现,以及一些控制它的附加属性。这应该怎么做?

+3

当孩子继承'StupidBehavior'时,这总是一种遗憾。 – 2011-05-10 16:34:50

回答

2

您可以创建另一个附属属性,其中包含由主行为作为子类替换被调用的详细实现。属性所持有的对象可能是非静态的,并且可以像state-object一样使用。

你也许可以放入一个属性这个问题,以及,其中property == null意味着关闭

1

你可以使用一个静态构造函数,形成Dictionary<DependencyProperty,EventHandler>具体DP映射到一个特定的处理程序和使用法DependencyPropertyChanged回调:

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]; 
     } 
    } 
} 

或者干脆做一个args.Propertyswitch。或者介于两者之间的东西涉及基于DependencyProperty的常用方法和分支。

我不确定为什么你的IsEnabled属性处理DependencyProperty类型的值,而不是像bool那样会产生更多语义的东西。

+0

谢谢!它确实应该是bool。复制粘贴错误=) – Jens 2011-05-11 06:28:33