Event Aggregators是解決這類問題的好方法。基本上有一個集中的類(爲了簡單起見,我們假設它是一個單例,並面對反單身傢伙可能的憤怒),負責將事件從一個對象轉移到另一個對象。有了您的類名的使用可能看起來像:
public class MainViewModel
{
public MainViewModel()
{
WordAddedEvent event = EventAggregator.Instance.GetEvent<WordAddedEvent>();
event.Subscribe(WordAdded);
}
protected virtual void WordAdded(object sender WordAddedEventArgs e)
{
// handle event
}
}
public class AddWordViewModel
{
//From the command
public void ExecuteAddWord(string word)
{
WordAddedEvent event = EventAggregator.Instance.GetEvent<WordAddedEvent>();
event.Publish(this, new WordAddedEventArgs(word));
}
}
這種模式的好處是,你可以很輕鬆地擴展您的應用程序具有的創造的話,多的ViewModels有興趣已添加詞語多種方式並且兩者之間沒有耦合,因此您可以根據需要添加和刪除它們。
如果你想避免單(和出於測試目的,我建議你這樣做),那麼它可能是值得探討依賴注入,雖然這確實是一個整體的其他問題。
好吧,最後的想法。我從重新閱讀您的問題中看到,您已經有了一些處理Word對象檢索和存儲的Word Service類。沒有理由說服務不能負責提升事件,因爲兩個ViewModel已經連接在一起了。雖然我仍然建議EventAggregator更加靈活,更好的解決方案,但YAGNI可以在這裏申請
public class WordService
{
public event EventHandler<WordAddedEventArgs> WordAdded;
public List<string> GetAllWords()
{
//return words
}
public void SaveWord(string word)
{
//Save word
if (WordAdded != null) WordAdded(this, new WordAddedEventArgs(word));
//Note that this way you lose the reference to where the word really came from
//probably doesn't matter, but might
}
}
public class MainViewModel
{
public MainViewModel()
{
//Add eventhandler to the services WordAdded event
}
}
要避免做雖然是通過調用命令介紹,您將創建的ViewModels之間的耦合是什麼在另一個ViewModel上,這會嚴重限制你擴展應用程序的選項(如果第二個ViewModel對新單詞產生了興趣,現在是AddWordViewModel的責任告訴那個單詞嗎?)
謝謝你非常詳細回答。將不得不挖掘:) :)很多樂趣:) – 2009-04-28 18:10:32