2009-04-28 50 views
20

火上查看事件在我的WPF應用程序,我有2個窗口(包括Windows系統有自己的視圖模型):WPF MVVM正確方法從視圖模型

  1. 應用程序的主窗口,與一堆話顯示錶(界到MainViewModel)

  2. 對話窗口,允許用戶添加新項目列表(綁定到AddWordViewModel)

MainViewModel有李的文章屬性st(此集合由其中一個服務類填充)綁定到主窗口的列表框

AddWordViewModel具有綁定到添加Word對話框的保存按鈕的SaveWordCommand。它的任務是獲取用戶輸入的文本並將其傳遞給服務類。

用戶點擊保存按鈕後,我需要通知MainViewModel重新加載服務中的文章。

我的想法是從AddWordViewModel

在MainViewModel揭露公共命令並執行它

什麼是它執行正確的方式?

謝謝!

回答

18

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的責任告訴那個單詞嗎?)

+0

謝謝你非常詳細回答。將不得不挖掘:) :)很多樂趣:) – 2009-04-28 18:10:32