Reputation: 1730
I have some academic question here. I read this question WPF MVVM Get Parent from VIEW MODEL and concluded that ViewModel
should not opens any windows itself. So I use Messenger
now to send message to ViewModel
's Window
and Window
opens other window - NewWindow
. It works fine, but what if NewWindow
does something and get some Result
has to be passed in MainWindow
for further actions? More detailed:
NewWindow
opened by button click in Window
(OpenNewWindowCommand) and made some calculations.NewWindow
got some Result
(does't matter what exactly is it) and rise a corresponding event - GotSomeResult
, where event arg is Result
.Result
has to be passed in MainWindow
to further processing, so I bind event handler to GotSomeResult
event. Below you can see all required code to illustrate this scenario.
MainWindow code-behind:
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
Messenger.Default.Register<NewWindowMessage>(this, OpenNewWindow);
}
private void OpenNewWindow(NewWindowMessage message)
{
var newWindow = new NewWindow();
var newWindowViewModel = (NewWindowViewModel) message.Target;
newWindowViewModel.GotSomeResult += ((MetaWindowViewModel)DataContext).ProcessResult;
newWindow.Owner = this;
newWindow.DataContext = newWindowViewModel;
newWindow.ShowDialog();
}
MainWindow ViewModel:
public void OpenNewWindowCommand()
{
Messenger.Default.Send(new NewWindowMessage(this, new NewWindowViewModel("OpenWindow"), String.Empty));
}
public void ProcessResult(Object someResult)
{
// Any actions with result
}
newWindowViewModel.GotSomeResult += ((MetaWindowViewModel)DataContext).ProcessResult; --- this string seems problem for me. Is it correct to get access to public method of ViewModel
right in theView
? Does it violent MVVM
pattern?
Upvotes: 1
Views: 109
Reputation: 2430
Why don't you hook the handler to GotSomeResult
at the VM level, ie :
public void OpenNewWindowCommand()
{
var newWindowViewModel = new NewWindowMessage(this, new NewWindowViewModel("OpenWindow"), String.Empty)
newWindowViewModel.GotSomeResult += this.ProcessResult;
Messenger.Default.Send();
}
It removes the references to your ViewModel in your codebehind (which indeed should be avoided):
private void OpenNewWindow(NewWindowMessage message)
{
var newWindow = new NewWindow();
newWindow.Owner = this;
newWindow.DataContext = message.Target;
newWindow.ShowDialog();
}
Upvotes: 2