3

我一直在玩行为,遇到了一个有趣的问题。这是我的行为:

public class AddNewBehavior : BaseBehavior<RadGridView, AddNewBehavior>
{
    public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached("IsEnabled", typeof(bool), typeof(AddNewBehavior), new FrameworkPropertyMetadata(false, OnIsEnabledChanged));

    public static void SetIsEnabled(DependencyObject obj, bool isEnabled)
    {
        obj.SetValue(IsEnabledProperty, isEnabled);
    }

    public static bool GetIsEnabled(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsEnabledProperty);
    } ... OnIsEnabledChanged(...)}

当我设置这样的样式时,这将非常有用:

<Style TargetType="telerikGridView:RadGridView">
    <Setter Property="Behaviors:AddNewBehavior.IsEnabled" Value="true" />
</Style>

但是如果我把它放在一个抽象类中

public abstract class BaseBehavior<TObj, TBehavior> : Behavior<TObj> 
    where TObj : DependencyObject
    where TBehavior : BaseBehavior<TObj, TBehavior>, new()
{
    public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached("IsEnabled", typeof(bool), typeof(TBehavior), new FrameworkPropertyMetadata(false, OnIsEnabledChanged));

    public static void SetIsEnabled(DependencyObject obj, bool isEnabled)
    {
        obj.SetValue(IsEnabledProperty, isEnabled);
    }

    public static bool GetIsEnabled(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsEnabledProperty);
    }

    public static void OnIsEnabledChanged(DependencyObject dpo, DependencyPropertyChangedEventArgs e)
    {
        BehaviorCollection behaviorCollection = Interaction.GetBehaviors(dpo);

        if ((bool)e.NewValue)
        {
            var firstOrDefault = behaviorCollection.Where(b => b.GetType() == typeof(TBehavior)).FirstOrDefault();

            if (firstOrDefault == null)
            {
                behaviorCollection.Add(new TBehavior());
            }
        }
    }
}

样式声明将与“值不能为空。属性名称:属性”一起粉碎。

想知道我做错了什么,在基类中使用 IsEnabled 代码会很棒。

谢谢,

4

1 回答 1

2

在基类的 IsEnabledProperty 定义中,尝试将其更改为:

public static readonly DependencyProperty IsEnabledProperty = 
  DependencyProperty.RegisterAttached(
    "IsEnabled", 
    typeof(bool), 
    typeof(BaseBehavior<TObj, TBehavior>), 
    new FrameworkPropertyMetadata(false, OnIsEnabledChanged)
  );

也就是说,不是TBehavior作为 DP OwnerType 传递,BaseBehavior<TObj, TBehavior>而是传入。

于 2010-09-09T21:16:10.897 回答