【发布时间】:2011-02-17 17:31:10
【问题描述】:
我正在开发一个项目,我正在使用中介者模式在 viewModel 和 View 之间进行通信。
问题在于,在消息中注册的方法与消息发送的次数一样多。
好吧,让我们写下我的问题。
从一个简单的菜单中,我有一个项目,我已经为它分配了一个命令
//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 次,你可以想象 :)
我怎样才能防止这种情况发生? 我必须以某种方式杀死消息吗?
好像写的很烂,我对消息传递(中介模式)很困惑,但我知道如果我习惯了它,事情会容易得多。
我将不胜感激任何帮助或建议。
谢谢
【问题讨论】: