From b52fb5b8def9d2c04a0103a825605c2e591a6c7f Mon Sep 17 00:00:00 2001 From: Curtis Wensley Date: Mon, 27 May 2024 14:39:20 -0700 Subject: [PATCH] Trigger DataContextChanged when parent change causes DataContext to be null --- src/Eto/Forms/Binding/BindableWidget.cs | 3 ++- .../UnitTests/Forms/DataContextTests.cs | 24 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/Eto/Forms/Binding/BindableWidget.cs b/src/Eto/Forms/Binding/BindableWidget.cs index 5abad73682..1efdecaf9c 100644 --- a/src/Eto/Forms/Binding/BindableWidget.cs +++ b/src/Eto/Forms/Binding/BindableWidget.cs @@ -93,9 +93,10 @@ public Widget Parent get => Properties.Get(Parent_Key); internal protected set { + var dataContext = DataContext; if (Properties.TrySet(Parent_Key, value)) { - if (!HasDataContext && !(DataContext is null)) + if (!HasDataContext && !ReferenceEquals(DataContext, dataContext)) { IsDataContextChanging = true; OnDataContextChanged(EventArgs.Empty); diff --git a/test/Eto.Test/UnitTests/Forms/DataContextTests.cs b/test/Eto.Test/UnitTests/Forms/DataContextTests.cs index 82808b70fd..754d21c1d5 100644 --- a/test/Eto.Test/UnitTests/Forms/DataContextTests.cs +++ b/test/Eto.Test/UnitTests/Forms/DataContextTests.cs @@ -436,6 +436,30 @@ public void ChangingDataContextShouldNotSetValues() => Shown( Assert.AreEqual(0, model1.SelectedIndex, "#3 - Model 1 was changed"); Assert.AreEqual(1, model2.SelectedIndex, "#4 - Model 2 was changed"); }); + + [Test] + public void RemovingFromParentShouldTriggerBindingChanged() => Invoke(() => + { + int parentDataContextChanged = 0; + int childDataContextChanged = 0; + var panel = new Panel(); + panel.DataContextChanged += (sender, e) => parentDataContextChanged++; + + panel.DataContext = new MyViewModelWithEquals { ID = 10 }; + Assert.AreEqual(1, parentDataContextChanged); + + var child = new Panel(); + child.DataContextChanged += (sender, e) => childDataContextChanged++; + + panel.Content = child; + Assert.AreEqual(1, childDataContextChanged); + Assert.AreSame(child.DataContext, panel.DataContext); + + panel.Content = null; + Assert.AreEqual(2, childDataContextChanged); + Assert.AreEqual(1, parentDataContextChanged); + Assert.IsNull(child.DataContext); + }); } }