Wpf样式和附加属性

3

我一直在研究行为(Behaviors),最近遇到了一个有趣的问题。

这是我的行为代码:

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个回答

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>

太棒了,解决了问题,非常感谢。昨晚我一定睡得很沉,所以没能成功。 - Calin

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