Skip to content

Instantly share code, notes, and snippets.

@CodingOctocat
Last active April 13, 2025 11:28
Show Gist options
  • Save CodingOctocat/8f46da82b8a596eac0b9282b588f230f to your computer and use it in GitHub Desktop.
Save CodingOctocat/8f46da82b8a596eac0b9282b588f230f to your computer and use it in GitHub Desktop.
AttachableForStyleBehavior
public class AttachableForStyleBehavior<TComponent, TBehavior> : Behavior<TComponent>
where TComponent : DependencyObject
where TBehavior : AttachableForStyleBehavior<TComponent, TBehavior>, new()
{
public static readonly DependencyProperty IsEnabledForStyleProperty =
DependencyProperty.RegisterAttached(
"IsEnabledForStyle",
typeof(bool),
typeof(AttachableForStyleBehavior<TComponent, TBehavior>),
new FrameworkPropertyMetadata(false, OnIsEnabledForStyleChanged));
public bool IsEnabledForStyle
{
get => (bool)GetValue(IsEnabledForStyleProperty);
set => SetValue(IsEnabledForStyleProperty, value);
}
private static void OnIsEnabledForStyleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is UIElement uie)
{
var behColl = Interaction.GetBehaviors(uie);
var existingBehavior = behColl.FirstOrDefault(b => b.GetType() == typeof(TBehavior)) as TBehavior;
if ((bool)e.NewValue == false && existingBehavior is not null)
{
behColl.Remove(existingBehavior);
}
else if ((bool)e.NewValue == true && existingBehavior is null)
{
behColl.Add(new TBehavior());
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment