【问题标题】:Problem with xamarin forms image when removing and adding it from parent layout从父布局中删除和添加 xamarin 表单图像时出现问题
【发布时间】:2021-12-08 11:29:16
【问题描述】:

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

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

请在下面找到代码sn-p

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获取完整示例

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

提前致谢,
维涅什·拉梅什。

【问题讨论】:

    标签: image xamarin.forms stream


    【解决方案1】:

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

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

       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);
    
        }
    

    【讨论】:

    • 感谢您的建议。我可以知道,有没有办法在不使其成为全局变量的情况下实现这一点?
    • YES,但您无法从流中加载图像。从每个平台的资源文件夹中设置图像。有关更多详细信息,请查看以下链接。 docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-11
    • 1970-01-01
    • 2020-03-07
    • 2019-08-09
    • 2019-05-01
    • 2016-11-27
    • 1970-01-01
    相关资源
    最近更新 更多