How to open / show a new window in MVVM using the mediator template?

I have a lot of new in the WPF and MVVM paradigm, and I try to absorb it. The problem I am facing is similar to the fact that many MVVM beginners are faced with the same thing, and there seems to be no easy approach. So, to keep the problem area problem simple here, just experimental work.

I have a MainWindow with a "New" button. I want to show an instance of NewWindow.xaml when I click on this button. How can I do this from MainWindowViewModel? Can a reseller template help? Please offer any good implementation recommendation.

I also have a Close button on MainWindow, and I want to exit the application when I click this one. And again I need help :(

+4
source share
2 answers

I had the same problem a while ago.

at least I use a very simple approach and I am satisfied. here is my solution.

in your view model you just need to write one line of code:

var result = this.uiDialogService.ShowDialog("Dialogwindow title goes here", newdialogwindowVMgoeshere); //do what you want with the dialogresult 
+2
source

I embed the dialog code in the View CodeBehind. I still direct the command through the ViewModel, but the ViewModel calls the View implementation and gets the result.

Suppose I have MainWindow View (xaml) and MainWindow ViewModel, and I want to save the file.

In the codebehind View (MainWindow.xaml.cs), I add code to create a dialog box and return the name of the save file:

  public FileInfo OpenSaveFileDialog(string title, string filter) { var dialog = new SaveFileDialog { Filter = filter, Title = title }; var result = dialog.ShowDialog(); if (!result.Value) return null; return new FileInfo(dialog.FileName); } 

In ViewModel, I have a DoSaveFile () method:

  public void DoSaveFile() { var file = OpenSaveFileDialog("Save File", "Super files (*.super)|*.super |All files (*.*)|*.*"); if (file == null) return; //Save logic... } public DelegateCommand SaveFile { get { return Get("SaveFile", new DelegateCommand(DoSaveFile, () => true)); } } 

In MainWindow.xaml, I have a button attached to a delegate command:

  <Button Content="Save File" Command="{Binding SaveFile}"/> 

Like MVP, this implementation is talkative, but it works great for testing and separating problems. It makes sense for me to leave the mechanics of opening a window to the View class, even thinking that it looks a bit like an active view.

+1
source

Source: https://habr.com/ru/post/1342381/


All Articles