从父布局中删除和添加xamarin表单图像时出现问题



描述
我创建了一个简单的Xamarin.Forms示例。在它中,我添加了一个图像,并通过ImageSource.FromSource()方法将图像作为流加载,然后将其删除并添加到布局中。

Xamarin.Forms UWP图像将消失
Xamarin.Forms Android无法访问关闭流异常抛出
Xamarin.Forms iOS尚未检查

请在下面找到代码片段

XAML:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ImageException.MainPage">
<ContentPage.Content>
<Grid x:Name="MainGrid">
<Image x:Name="image" />
<Button Text="Click_Me"
Clicked="Button_Clicked"
VerticalOptions="End" />
</Grid>
</ContentPage.Content>
</ContentPage>

C#:

namespace ImageException
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
var assembly = typeof(MainPage).Assembly;
string path = "ImageException";
var stream = assembly.GetManifestResourceStream($"{path}.Image.Image.png");
image.Source = ImageSource.FromStream(() => stream);
}
private void Button_Clicked(object sender, EventArgs e)
{
MainGrid.Children.Remove(image);
MainGrid.Children.Add(image);
}
}
}

请从下面的链接获取完整的样本https://github.com/VigneshRameshh/XamarinFormsImageException

有人能建议如何在从布局中删除和添加后保留图像吗?

提前感谢,
Vignesh Ramesh。

我检查了您的代码,可以重现您的异常。

如果你想解决这个问题,你可以使用下面的代码。

Stream stream;
Assembly assembly;
string path;
public Page18()
{
InitializeComponent();
assembly = typeof(MainPage).Assembly;
path = "App14";
stream = assembly.GetManifestResourceStream($"{path}.Image.beach.jpg");
image.Source = ImageSource.FromStream(() => stream);
}
private void Button_Clicked(object sender, EventArgs e)
{
stream = assembly.GetManifestResourceStream($"{path}.Image.beach.jpg");
MainGrid.Children.Remove(image);
MainGrid.Children.Add(image);
}