3
我一直玩的行爲,我遇到了一個有趣的問題。 這裏是我的行爲:Wpf風格和附加屬性
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代碼將會非常棒。
感謝,
偉大的,這沒有竅門,10倍。我試過這個時,一定是昨天晚上睡得很熟。 – Calin 2010-09-10 06:35:45