从另一个帮助程序类更新视图模型的可观察集合

本文关键字:观察 集合 模型 新视图 另一个 帮助程序 更新 | 更新日期: 2023-09-27 18:34:25

我有一个带有 ObservableCollection 的 ViewModel,我

有一个长函数,我将使用它来更新 ObservableCollection 项目,但是函数太长了,我不想把它放在 ViewModel 中。

我想直接在 ObservableCollection 上进行更新,以便在进程运行时可以看到视图上的更改。

我想到了以下

  • 通过引用发送可观察集合
  • 将当前项发送到函数并返回更新的对象
  • 使我的可观察集合静态
  • 将更新功能放在我的视图模型中,但这会使我的视图模型又大又乱
将有很多

不同的功能将适用于此集合,在这种情况下,最佳编程实践是什么?

从另一个帮助程序类更新视图模型的可观察集合

如果您正在处理数据,然后将处理后的数据传递给视图,那么我认为以下选项应该是一种可能的解决方案。

以下解决方案将处理数据,同时也会通知视图更改。

public class MyViewModel : INotifyPropertyChanged
{
    private ObservableCollection<string> _unprocessedData = new ObservableCollection<string>();
    private ObservableCollection<string> _processedData = new ObservableCollection<string>();
    private static object _lock = new object();
    public event PropertyChangedEventHandler PropertyChanged;
    public ObservableCollection<string> Collection { get { return _processedData; } }//Bind the view to this property
    public MyViewModel()
    {
        //Populate the data in _unprocessedData
        BindingOperations.EnableCollectionSynchronization(_processedData, _lock); //this will ensure the data between the View and VM is not corrupted
        ProcessData();
    }
    private async void ProcessData()
    {
        foreach (var item in _unprocessedData)
        {
            string result = await Task.Run(() => DoSomething(item));
            _processedData.Add(result);
            //NotifyPropertyChanged Collection
        }
    }
    private string DoSomething(string item)
    {
        Thread.Sleep(1000);
        return item;
    }
}

DoSomething 方法可以在 ViewModel 之外的某个其他类中定义。

我希望这有所帮助。