diff --git a/src/Controls/src/Core/AppThemeBinding.cs b/src/Controls/src/Core/AppThemeBinding.cs index fb2cc0a0ce6a..cc9bbf335cc3 100644 --- a/src/Controls/src/Core/AppThemeBinding.cs +++ b/src/Controls/src/Core/AppThemeBinding.cs @@ -7,6 +7,7 @@ class AppThemeBinding : BindingBase { WeakReference _weakTarget; BindableProperty _targetProperty; + bool _attached; internal override BindingBase Clone() => new AppThemeBinding { @@ -21,8 +22,7 @@ internal override void Apply(bool fromTarget) { base.Apply(fromTarget); ApplyCore(); - - AttachEvents(); + SetAttached(true); } internal override void Apply(object context, BindableObject bindObj, BindableProperty targetProperty, bool fromBindingContextChanged = false) @@ -31,14 +31,12 @@ internal override void Apply(object context, BindableObject bindObj, BindablePro _targetProperty = targetProperty; base.Apply(context, bindObj, targetProperty, fromBindingContextChanged); ApplyCore(); - - AttachEvents(); + SetAttached(true); } internal override void Unapply(bool fromBindingContextChanged = false) { - DetachEvents(); - + SetAttached(false); base.Unapply(fromBindingContextChanged); _weakTarget = null; _targetProperty = null; @@ -51,7 +49,7 @@ void ApplyCore(bool dispatch = false) { if (_weakTarget == null || !_weakTarget.TryGetTarget(out var target)) { - DetachEvents(); + SetAttached(false); return; } @@ -123,18 +121,23 @@ target is VisualElement ve && }; } - void AttachEvents() + void SetAttached(bool value) { - DetachEvents(); - - if (Application.Current != null) - Application.Current.RequestedThemeChanged += OnRequestedThemeChanged; - } - - void DetachEvents() - { - if (Application.Current != null) - Application.Current.RequestedThemeChanged -= OnRequestedThemeChanged; + var app = Application.Current; + if (app != null && _attached != value) + { + if (value) + { + // Going from false -> true + app.RequestedThemeChanged += OnRequestedThemeChanged; + } + else + { + // Going from true -> false + app.RequestedThemeChanged -= OnRequestedThemeChanged; + } + _attached = value; + } } } } \ No newline at end of file