Суммируя ответы и эту замечательную статью Blend Behaviors in Styles , я пришел к этому родовому короткому и удобному решению:
Я сделал общий класс, который может быть унаследован любым поведением .
public class AttachableForStyleBehavior : Behavior
where TComponent : System.Windows.DependencyObject
where TBehavior : AttachableForStyleBehavior , new ()
{
public static DependencyProperty IsEnabledForStyleProperty =
DependencyProperty.RegisterAttached("IsEnabledForStyle", typeof(bool),
typeof(AttachableForStyleBehavior), new FrameworkPropertyMetadata(false, OnIsEnabledForStyleChanged));
public bool IsEnabledForStyle
{
get { return (bool)GetValue(IsEnabledForStyleProperty); }
set { SetValue(IsEnabledForStyleProperty, value); }
}
private static void OnIsEnabledForStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
UIElement uie = d as UIElement;
if (uie != null)
{
var behColl = Interaction.GetBehaviors(uie);
var existingBehavior = behColl.FirstOrDefault(b => b.GetType() ==
typeof(TBehavior)) as TBehavior;
if ((bool)e.NewValue == false && existingBehavior != null)
{
behColl.Remove(existingBehavior);
}
else if ((bool)e.NewValue == true && existingBehavior == null)
{
behColl.Add(new TBehavior());
}
}
}
}
Таким образом, вы можете просто повторно использовать его с большим количеством компонентов, таких как:
public class ComboBoxBehaviour : AttachableForStyleBehavior
{ ... }
И в XAML достаточно объявить: