开发者

Wpf styles and attached properties

I've been playing with b开发者_运维问答ehaviors and I came across a interesting issue. Here is my behavior:

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(...)}

This will work great when I set the styles like this:

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

But if I put this in an abstract class

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

The style declaration will crush with "Value cannot be null. Property name: property".

Wonder what am I doing wrong, it will be great to have to IsEnabled code in a base class.

Thanks,


In your IsEnabledProperty definition in the base class, try changing it to:

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

that is, instead of passing TBehavior as the DP OwnerType, pass in BaseBehavior<TObj, TBehavior> instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜