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 inWindow
(OpenNewWindowCommand) and made some calculations.- After calculations
NewWindow
got someResult
(does't matter what exactly is it) and rise a corresponding event -GotSomeResult
, where event arg isResult
. - This
Result
has to be passed inMainWindow
to further processing, so I bind event handler toGotSomeResult
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?