2011-02-17 14 views
0

我正在開發一個項目,我正在使用介體模式進行viewModel和View之間的通信。MVVM light,來自中介模式的消息應該手動處理?

問題是,註冊消息的方法執行的次數與發送消息的次數相同。

好吧,讓我們寫下我的問題。

從一個簡單的菜單我有一個項目我已經分配給它的指令

//MainWindow.xaml 
<awc:ImageButton IsToolStyle="True" Orientation="Vertical" ImageSource="" Command="{Binding ShowPricesWindowCommand}">Prices</awc:ImageButton> 


//MainWIndow ViewModel 
public ICommand ShowPricesWindowCommand { 
     get { return new RelayCommand(ShowPricesWindowExecute); } 
    } 
void ShowPricesWindowExecute() { 
     Messenger.Default.Send(new NotificationMessage<Hotel>(this, SelectedHotel, "ShowPricesWindow"), 
           "ShowPricesWindow"); 
    } 


//MainWindow.xaml.cs 
Messenger.Default.Register<NotificationMessage<Hotel>>(this, "ShowPricesWindow", HotelPriceMessageReceived); 

private void HotelPriceMessageReceived(NotificationMessage<Hotel> selectedHotel) { 
     var roomPrices = new RoomPrices();//This view has the RoomPriceViewModel as dataContext 
     roomPrices.Show(); 
     //via messaging I am sending the selectedHotel object 
     Messenger.Default.Send(new NotificationMessage<Hotel>(this, selectedHotel.Content, "ShowPricesWindow"), 
           "ShowPricesWindow2"); 
    } 

從RoomPricesViewModel我做了一個簡單的計算,我需要關閉視圖事後打開另一個。

public RoomPricesViewModel(IDialogService dialogService) { 
     this._dialog = dialogService; 
     Messenger.Default.Register<NotificationMessage<Hotel>>(this, "ShowPricesWindow2", NotificationMessageReceived); 
    } 

    private void NotificationMessageReceived(NotificationMessage<Hotel> selectedHotel) { 
     this.SelectedHotel = selectedHotel.Content; 
     LoadRooms(); 
    } 

void LoadRooms() { 
     if (rooms.Count == 0) { 
      dialogResponse = _dialog.ShowMessage("Display a message;", "", DialogButton.YesNo, DialogImage.Warning); 
      switch (dialogResponse) { 
       case DialogResponse.Yes: 
        //close the RoomPrices window and open the RoomTypesWindow 
        Messenger.Default.Send(new NotificationMessage<Hotel>(this, this.SelectedHotel, "CloseWindowAndOpenRoomTypes"), "CloseWindowAndOpenRoomTypes"); 
        return; 
        break; 
       case DialogResponse.No: 
        break; 
      } 
     } 
    } 

代碼似乎工作,但如果我按一下按鈕,一個視圖打開,它會提示我有一個消息,如果我點擊是,當前視圖關閉,另一個是開放。

如果我再次點擊按鈕,窗口關閉,兩個窗口打開而不是一個。

如果點擊10次,你能想象:)

我怎麼能避免這種情況? 我必須殺死消息嗎?

這似乎寫得很差,我一直很困惑與消息傳遞(中介模式),但我知道如果我習慣了它,事情會容易得多。

我會感謝任何幫助或建議。

感謝

回答

0

解決方案

的問題是,我的消息,並多次在窗口中打開很多次的消息被註冊的所有窗口的構造函數註冊。 因此,該窗口會多次打開「NotificationMessage」註冊。

我簡單來看,這種

public RoomPricesViewModel(IDialogService dialogService) { 
     Messenger.Default.Register<NotificationMessage<Hotel>>(this, "ShowPricesWindow", NotificationMessageReceived); 
    } 

    private void NotificationMessageReceived(NotificationMessage<Hotel> selectedHotel) { 
     //code 
     Messenger.Default.Unregister(this); 
    } 

和問題就解決了。