当 ObservableCollection 中的模型属性发生更改时更新 UI?

msh*_*hwf 5 c# mvvm mvvm-light xamarin xamarin.forms

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

 public class ImageModel 
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string imageUrl { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

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

 public bool UpVoted { get; set; }
Run Code Online (Sandbox Code Playgroud)

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

    private void OnVoting(ImageModel image)
    {
        Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted;
    }
Run Code Online (Sandbox Code Playgroud)

问题是 UI 没有更新,为了确保我理解问题,我将模型转换为视图模型并对属性进行了所需的更改UpVoted(我正在使用 MVVM light 库)

bool upVoted;
        public bool UpVoted
        {
            get { return upVoted; }
            set
            {
                Set(ref upVoted, value);
            }
        }
Run Code Online (Sandbox Code Playgroud)

现在它可以工作了,所以我需要将其绑定UpVoted到用户界面,这样每当它发生变化时它就会更新

小智 2

首先你的模型类必须继承自 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 ); }
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后和MvxValueConverter 你一起准备出发