Wpf样式和附加属性

时间:2010-09-09 19:58:56

标签: wpf styles dependency-properties attached-properties

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

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代码会很棒。

谢谢,

1 个答案:

答案 0 :(得分: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>