会更新ViewModel中的ObservableCollecti

会更新ViewModel中的ObservableCollecti

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

问题描述

假设我有一个模型类Data,我想为其创建DataViewModelDataView.数据类如下所示:

Let's say I have a model class Data and I would like to create DataViewModel and DataView for it. The data class looks like this:

public class Data
{
    public Data()
    {
        RandomData = new List<String>();
    }

    public List<String> RandomData {get; set;}
}

我想创建封装RandomData属性的DataViewModel.我需要绑定到某些ListView中的RandomData属性,并在基础模型的RandomData更改时对其进行更新.

I want to create DataViewModel that encapsulates RandomData property. I need to bind to that RandomData property in some ListView and have it updated when the underlying model's RandomData changes.

如果我这样做:

public class DataViewModel
{
    private Data _data;

    public DataViewModel(Data data)
    {
        _data = data;
        RandomData = new ObservableCollection<String>(_data.RandomData);
    }

    public ObservableCollection<String> RandomData {get; set;}
}

然后我没有收到任何更新. (我知道这只是复制列表,我只是用它来说明要点).如果我在RandomData属性上使用了INotifyPropertyChanged,那么我只会收到分配给它的新列表的通知.我该如何检查内容的更改?首选的方法是什么?

then I don't receive any updates. (I am aware that is just copying the list, I just use it to get the point across). If I used INotifyPropertyChanged on the RandomData property then I'd only receive notifications of new Lists being assigned to it. How do I check for change to the contents instead? What is the preferred way of doing this?

谢谢您的任何建议

推荐答案

对于此特定示例,我很想更改您的模型以使用ObservableCollection

For this specific example I would be tempted to change your model to use an ObservableCollection

public class Data
{
    public Data()
    {
        RandomData = new ObservableCollection<String>();
    }

    public ObservableCollection<String> RandomData {get; set;}
}

,然后在您的视图模型中将其公开为 ReadOnlyObservableCollection .请注意,ReadOnlyObservableCollection是原始ObservableCollection的包装.该数据不会被复制,并且来自原始集合的更改通知将由ReadOnlyObservableCollection反映出来.

and then expose this in your view model as a ReadOnlyObservableCollection. Note that ReadOnlyObservableCollection is a wrapper over the original ObservableCollection. The data isn't copied and change notifications from the original collection are reflected by the ReadOnlyObservableCollection.

public class DataViewModel
{
    public DataViewModel(Data data)
    {
        RandomData = new ReadOnlyObservableCollection<String>(data.RandomData);
    }

    public ReadOnlyObservableCollection<String> RandomData {get; private set;}
}

这是假设您当然希望视图模型RandomData是只读的.

This is assuming that you want the view model RandomData to be read-only of course.

这篇关于当模型中的列表更改时,不会更新ViewModel中的ObservableCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 11:26