【问题标题】:How to hide/unload a CachedImage in xamarin forms如何在 xamarin 表单中隐藏/卸载 CachedImage
【发布时间】:2021-07-04 05:31:18
【问题描述】:

我还是 Xamarin 表单的新手,现在我正在使用 Ffimagloading 库通过我的视图模型的“DisplayImage”属性显示 gif。但是在满足某些条件后,我想隐藏/卸载图像,使其不再存在。 这是我视图中的 CachedImage:

                <ffimage:CachedImage Grid.Column="0"
                                   Source="{Binding DisplayImage}" />

这是我的 ViewModel 中对应的部分:

    private ImageSource displayImage;

    public void DownloadAndAssignImage() {
        try
        {
            var response = await this.DownloadFile(new Uri("..."));
            if (response != null)
            {
                this.DisplayImage = ImageSource.FromStream(() => new MemoryStream(response));
                
            }
        }
        catch (Exception e)
        {
            Log.Error(e);
        }
    }


    public void HideImage()
    {
        // does not work
        this.DisplayImage = null;
        
        // does not work too
        this.DisplayImage = new byte[0];
    }

    public ImageSource DisplayImage
    {
        get => this.displayImage;
        set
        {
            this.displayImage= value;
            this.RaisePropertyChanged();
        }
    }

我怎样才能做到这一点,以便在通过“DownloadAndAssignImage()”将 ImageSource 分配给 CachedImage 后,它不再显示任何内容?将 ImageSource 设置为 null 或空的 byte[] 数组不起作用。我究竟需要如何修改“HideImage()”方法?

提前感谢您的帮助!

【问题讨论】:

    标签: c# xamarin.forms mvvm-light ffimageloading


    【解决方案1】:

    使用IsVisible

    <ffimage:CachedImage Grid.Column="0" IsVisible="{Binding ImageVisible}"
                                   Source="{Binding DisplayImage}" />
    

    然后在你的虚拟机中(你需要实现 INotifyPropertyChanged)

    ImageVisible = false;
    

    【讨论】:

    • 感谢您的回答。不幸的是,我稍微缩短了代码。 CachedImage 中还有一个背景,我希望它独立于图像源显示。如果我将可见性设置为 False,背景也会消失。这就是为什么我正在寻找一种方法来重置 Source 属性。
    • 使用占位符图像可能是最简单的方法
    • 有方便的方法吗?
    • @Ro0f3r 当我为 CachedImage 添加背景和有效图像源时,它只显示图像源,不显示背景。如果我设置CachedImage source=null,背景也无法显示,所以按照jason的意见,可以使用placeholder image:forums.xamarin.com/discussion/94350/…
    猜你喜欢
    • 2019-04-02
    • 1970-01-01
    • 2016-11-19
    • 2017-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    • 2021-01-07
    相关资源
    最近更新 更多