diff --git a/src/CommunityToolkit/Xamarin.CommunityToolkit/Behaviors/BaseBehavior.shared.cs b/src/CommunityToolkit/Xamarin.CommunityToolkit/Behaviors/BaseBehavior.shared.cs index 51840d367..2529f5f6f 100644 --- a/src/CommunityToolkit/Xamarin.CommunityToolkit/Behaviors/BaseBehavior.shared.cs +++ b/src/CommunityToolkit/Xamarin.CommunityToolkit/Behaviors/BaseBehavior.shared.cs @@ -21,6 +21,30 @@ static readonly FieldInfo? bindingField protected TView? View { get; private set; } + internal bool TrySetBindingContext(Binding binding) + { + if (!IsBound(BindingContextProperty)) + { + SetBinding(BindingContextProperty, defaultBindingContextBinding = binding); + return true; + } + + return false; + } + + internal bool TryRemoveBindingContext() + { + if (defaultBindingContextBinding != null) + { + RemoveBinding(BindingContextProperty); + defaultBindingContextBinding = null; + + return true; + } + + return false; + } + protected virtual void OnViewPropertyChanged(object? sender, PropertyChangedEventArgs e) { } @@ -30,28 +54,17 @@ protected override void OnAttachedTo(TView bindable) base.OnAttachedTo(bindable); View = bindable; bindable.PropertyChanged += OnViewPropertyChanged; - - if (!IsBound(BindingContextProperty)) + TrySetBindingContext(new Binding { - defaultBindingContextBinding = new Binding - { - Path = BindingContextProperty.PropertyName, - Source = bindable - }; - SetBinding(BindingContextProperty, defaultBindingContextBinding); - } + Path = BindingContextProperty.PropertyName, + Source = bindable + }); } protected override void OnDetachingFrom(TView bindable) { base.OnDetachingFrom(bindable); - - if (defaultBindingContextBinding != null) - { - RemoveBinding(BindingContextProperty); - defaultBindingContextBinding = null; - } - + TryRemoveBindingContext(); bindable.PropertyChanged -= OnViewPropertyChanged; View = null; } diff --git a/src/CommunityToolkit/Xamarin.CommunityToolkit/Behaviors/Validators/MultiValidationBehavior.shared.cs b/src/CommunityToolkit/Xamarin.CommunityToolkit/Behaviors/Validators/MultiValidationBehavior.shared.cs index f07a7cc12..f042fc506 100644 --- a/src/CommunityToolkit/Xamarin.CommunityToolkit/Behaviors/Validators/MultiValidationBehavior.shared.cs +++ b/src/CommunityToolkit/Xamarin.CommunityToolkit/Behaviors/Validators/MultiValidationBehavior.shared.cs @@ -92,7 +92,7 @@ void OnChildrenCollectionChanged(object? sender, NotifyCollectionChangedEventArg { foreach (var child in e.NewItems.OfType()) { - child.SetBinding(BindingContextProperty, new Binding + child.TrySetBindingContext(new Binding { Path = BindingContextProperty.PropertyName, Source = this @@ -103,7 +103,7 @@ void OnChildrenCollectionChanged(object? sender, NotifyCollectionChangedEventArg if (e.OldItems != null) { foreach (var child in e.OldItems.OfType()) - child.RemoveBinding(BindingContextProperty); + child.TryRemoveBindingContext(); } } }