2013-10-08 32 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之外的其他類中定義。

我希望這會有所幫助。