From 939d80788b94829801a0a909b711050631e86e6d Mon Sep 17 00:00:00 2001 From: Steven Kirk Date: Fri, 9 Aug 2019 14:16:05 +0200 Subject: [PATCH] Added failing test for #2823. --- .../ContentPresenterTests_InTemplate.cs | 53 ++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/tests/Avalonia.Controls.UnitTests/Presenters/ContentPresenterTests_InTemplate.cs b/tests/Avalonia.Controls.UnitTests/Presenters/ContentPresenterTests_InTemplate.cs index 952180d21b..6ab9c345d4 100644 --- a/tests/Avalonia.Controls.UnitTests/Presenters/ContentPresenterTests_InTemplate.cs +++ b/tests/Avalonia.Controls.UnitTests/Presenters/ContentPresenterTests_InTemplate.cs @@ -1,7 +1,11 @@ // Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. +using System; +using System.Collections.Generic; +using System.ComponentModel; using System.Linq; +using System.Reactive.Linq; using Avalonia.Controls.Presenters; using Avalonia.Controls.Templates; using Avalonia.Data; @@ -256,7 +260,6 @@ namespace Avalonia.Controls.UnitTests.Presenters Assert.IsType(target.Child); } - [Fact] public void Should_Not_Bind_Old_Child_To_New_DataContext() { @@ -281,6 +284,34 @@ namespace Avalonia.Controls.UnitTests.Presenters target.Content = 42; } + [Fact] + public void Should_Not_Bind_Child_To_Wrong_DataContext_When_Removing() + { + // Test for issue #2823 + var canvas = new Canvas(); + var (target, host) = CreateTarget(); + var viewModel = new TestViewModel { Content = "foo" }; + var dataContexts = new List(); + + target.Bind(ContentPresenter.ContentProperty, (IBinding)new TemplateBinding(ContentControl.ContentProperty)); + canvas.GetObservable(ContentPresenter.DataContextProperty).Subscribe(x => dataContexts.Add(x)); + + host.DataTemplates.Add(new FuncDataTemplate((_, __) => canvas)); + host.Bind(ContentControl.ContentProperty, new Binding(nameof(TestViewModel.Content))); + host.DataContext = viewModel; + + Assert.Same(canvas, target.Child); + + viewModel.Content = 42; + + Assert.Equal(new object[] + { + null, + "foo", + null, + }, dataContexts); + } + [Fact] public void Should_Set_InheritanceParent_Even_When_LogicalParent_Is_Already_Set() { @@ -333,5 +364,25 @@ namespace Avalonia.Controls.UnitTests.Presenters { public IControl Child { get; set; } } + + private class TestViewModel : INotifyPropertyChanged + { + private object _content; + + public object Content + { + get => _content; + set + { + if (_content != value) + { + _content = value; + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Content))); + } + } + } + + public event PropertyChangedEventHandler PropertyChanged; + } } }