附加行为的继承

4
我希望能够在WPF应用程序中实现一组类似的附加行为。由于它们都共享一部分样板代码,我不想为每个行为重复编写,因此我想创建一个基本行为并从中继承。 但由于附加行为内部的所有内容都是静态的,我不知道该如何做。
例如,考虑这个行为,它会在鼠标按下时执行一个方法(真正的行为当然会做一些事件处理程序无法轻易完成的事情):
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
孩子继承“愚蠢行为”总是令人惋惜。 - Dan J
2个回答

2
您可以创建另一个附加属性,其中包含被主要行为调用的详细实现作为子类替换。该属性所持有的对象可以是非静态的,并且可以像状态对象一样使用。
您也可以将其适配到一个属性中,其中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.Property上进行switch。或者介于两者之间,涉及一个常见的方法,并基于DependencyProperty进行分支。
而我不确定为什么你的IsEnabled属性处理的是DependencyProperty类型的值,而不是更符合语义的bool类型。

谢谢!确实应该是布尔类型。这是复制粘贴错误 =) - Jens

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接