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.
source share