2013-10-08 29 views
0

我有一个ViewModel与ObservableCollection,我有一个很长的函数,我将用它来更新ObservableCollection项目,但是这个函数很长,我不想把它放在ViewModel里面。从另一个辅助类更新视图模型的可观察集合

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

我想到了followig

  • 由参
  • 发送的ObservableCollection发送当前项目的功能和返回更新 对象
  • 使我的ObservableCollection静态
  • puting更新功能在我的ViewModel但这将使我ViewModel大和凌乱

会有很多不同的功能在这个集合上工作,在这种情况下什么是最好的编程实践?

回答

1

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

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

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之外的其他类中定义。

我希望这会有所帮助。