Last active
April 13, 2025 11:28
-
-
Save CodingOctocat/8f46da82b8a596eac0b9282b588f230f to your computer and use it in GitHub Desktop.
AttachableForStyleBehavior
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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