Skip to content

Commit 711b2a7

Browse files
authored
Fix ReactiveUI regression, when DataContext type is different (#15423)
1 parent d5ca06f commit 711b2a7

File tree

3 files changed

+22
-4
lines changed

3 files changed

+22
-4
lines changed

src/Avalonia.ReactiveUI/ReactiveUserControl.cs

+3-2
Original file line numberDiff line numberDiff line change
@@ -48,14 +48,15 @@ protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs chang
4848

4949
if (change.Property == DataContextProperty)
5050
{
51-
if (Object.ReferenceEquals(change.OldValue, ViewModel))
51+
if (ReferenceEquals(change.OldValue, ViewModel)
52+
&& change.NewValue is null or TViewModel)
5253
{
5354
SetCurrentValue(ViewModelProperty, change.NewValue);
5455
}
5556
}
5657
else if (change.Property == ViewModelProperty)
5758
{
58-
if (Object.ReferenceEquals(change.OldValue, DataContext))
59+
if (ReferenceEquals(change.OldValue, DataContext))
5960
{
6061
SetCurrentValue(DataContextProperty, change.NewValue);
6162
}

src/Avalonia.ReactiveUI/ReactiveWindow.cs

+3-2
Original file line numberDiff line numberDiff line change
@@ -48,14 +48,15 @@ protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs chang
4848

4949
if (change.Property == DataContextProperty)
5050
{
51-
if (Object.ReferenceEquals(change.OldValue, ViewModel))
51+
if (ReferenceEquals(change.OldValue, ViewModel)
52+
&& change.NewValue is null or TViewModel)
5253
{
5354
SetCurrentValue(ViewModelProperty, change.NewValue);
5455
}
5556
}
5657
else if (change.Property == ViewModelProperty)
5758
{
58-
if (Object.ReferenceEquals(change.OldValue, DataContext))
59+
if (ReferenceEquals(change.OldValue, DataContext))
5960
{
6061
SetCurrentValue(DataContextProperty, change.NewValue);
6162
}

tests/Avalonia.ReactiveUI.UnitTests/ReactiveUserControlTest.cs

+16
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,22 @@ public void Should_Inherit_DataContext()
134134
Assert.Same(vm2, view.ViewModel);
135135
}
136136

137+
// https://github.com/AvaloniaUI/Avalonia/issues/15060
138+
[Fact]
139+
public void Should_Not_Inherit_DataContext_Of_Wrong_Type()
140+
{
141+
var view = new ExampleView();
142+
var root = new TestRoot(view);
143+
144+
Assert.Null(view.DataContext);
145+
Assert.Null(view.ViewModel);
146+
147+
root.DataContext = this;
148+
149+
Assert.Same(this, view.DataContext);
150+
Assert.Null(view.ViewModel);
151+
}
152+
137153
[Fact]
138154
public void Should_Not_Overlap_Change_Notifications()
139155
{

0 commit comments

Comments
 (0)