Skip to content

Commit a5821bc

Browse files
PureWeenrmarinho
authored andcommitted
Clear Parent on old image source (#29481)
1 parent aac1ddc commit a5821bc

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

src/Controls/src/Core/ImageElement.cs

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,12 @@ static void OnImageSourceChanged(BindableObject bindable, object oldValue, objec
2727
{
2828
var newSource = (ImageSource)newValue;
2929
var image = (IImageElement)bindable;
30-
if (newSource != null && image != null)
30+
31+
if (newSource is not null && image is not null)
32+
{
3133
newSource.SourceChanged += image.OnImageSourceSourceChanged;
34+
}
35+
3236
ImageSourceChanged(bindable, newSource);
3337
}
3438

@@ -37,8 +41,16 @@ static void OnImageSourceChanging(BindableObject bindable, object oldValue, obje
3741
var oldSource = (ImageSource)oldValue;
3842
var image = (IImageElement)bindable;
3943

40-
if (oldSource != null && image != null)
41-
oldSource.SourceChanged -= image.OnImageSourceSourceChanged;
44+
if (oldSource is not null)
45+
{
46+
if (image is not null)
47+
{
48+
oldSource.SourceChanged -= image.OnImageSourceSourceChanged;
49+
}
50+
51+
oldSource.Parent = null;
52+
}
53+
4254
ImageSourceChanging(oldSource);
4355
}
4456

src/Controls/tests/Core.UnitTests/ImageSourceTests.cs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,5 +167,16 @@ public async Task CancelCompletes()
167167
await ((IStreamImageSource)imageSource).GetStreamAsync();
168168
await imageSource.Cancel(); // This should complete!
169169
}
170+
171+
[Fact]
172+
public void SettingNewImageeSourceClearsParentOnOldImageSource()
173+
{
174+
var image = new Image { Source = "File.png" };
175+
var imageSource = image.Source;
176+
Assert.Equal(image, imageSource.Parent);
177+
image.Source = "File2.png";
178+
Assert.Null(imageSource.Parent);
179+
Assert.Equal(image, image.Source.Parent);
180+
}
170181
}
171-
}
182+
}

0 commit comments

Comments
 (0)