当ObservableCollection中的模型属性更改时

当ObservableCollection中的模型属性更改时

本文介绍了当ObservableCollection中的模型属性更改时,是否要更新UI?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个视图,其中包含一组从Web服务获取的图像我在此类课程的列表中收到它们:

I have a view that has a group of images I get from a web serviceI receive them in a list of this class:

 public class ImageModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string imageUrl { get; set; }
    }

在每个图像下方,我都显示一个向上投票按钮,因此我在上面的模型中添加了另一个bool属性:

under each image I show an up-vote button, so I added another bool property to the model above:

 public bool UpVoted { get; set; }

显示这些图像的ListView绑定到ObservableCollection<ImageModel >,我想通过转换器将投票图标更改,该转换器将UpVoted的值转换为相应的图标,当用户单击投票图标时:命令执行此方法:

the ListView that shows these images is bound to an ObservableCollection<ImageModel > , I want to change the voting icon through a converter that convert the value of UpVoted to the corresponding icon, when the user click the voting icon: a command execute this method:

    private void OnVoting(ImageModel image)
    {
        Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted;
    }

问题是用户界面没有更新,并且为了确保我理解该问题,我将模型转换为View模型,并对UpVoted属性进行了必要的更改(我正在使用MVVM光源库)

the problem is that the UI is not updated, and to make sure that I understood the problem I turned the model to a View model and made the required changes to the UpVoted property (I'm using MVVM light library)

bool upVoted;
        public bool UpVoted
        {
            get { return upVoted; }
            set
            {
                Set(ref upVoted, value);
            }
        }

,现在可以使用了,所以我需要将UpVoted绑定到用户界面,以便每当它更改时都会对其进行更新

and it works now,so I need to bind the UpVoted to the UI, so it's updated whenever it changed

推荐答案

第一您的模型类必须继承自MvxNotifyPropertyChanged

firstyour model class must inherit from MvxNotifyPropertyChanged

public class ImageModel : MvxNotifyPropertyChanged
    {
        public int Id { get; set; }
        public string Name { get; set; }
        private bool upVoted ;
        public bool UpVoted
        {
            get { return upVoted ; }
            set { upVoted = value; RaisePropertyChanged(() => UpVoted ); }
        }
    }

然后与MvxValueConverter准备出发

这篇关于当ObservableCollection中的模型属性更改时,是否要更新UI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 11:26