0
votes

I have been reading about the best way to open dialogs using PRISM and opening them the MVVM way, however what I have found so far seems to only work with custom dialogs. I'd like to be able to open a CommonOpenFileDialog when a button is clicked but I am very confused how I can do this while adhering to the MVVM pattern.

I can accomplish this using the code behind but I would like to avoid this if possible, but the problem I run into here is how I can then pass the dialog result to the view model from the code behind. Would an EventAggregator be acceptable here?

This is my SelectFolderDialog class which opens the dialog. This is currently called from my views code behind:

public class SelectFolderDialog
{

    public string SelectFolder()
    {

        var folderSelectorDialog = new CommonOpenFileDialog();
        folderSelectorDialog.EnsureReadOnly = true;
        folderSelectorDialog.IsFolderPicker = true;
        folderSelectorDialog.AllowNonFileSystemItems = false;
        folderSelectorDialog.Multiselect = false;
        folderSelectorDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        folderSelectorDialog.Title = "Select Folder";
        folderSelectorDialog.ShowDialog();

        string SelectedFolderPath = folderSelectorDialog.FileName;
        Console.WriteLine(SelectedFolderPath);

        return SelectedFolderPath;


    }
}
2

2 Answers

0
votes

The most MVVMy way is to have a SystemDialogService that you inject into your VMs, that has a method GetOpenFileDialogPath or something, that does exactly what your code does.

That way you can easily mock it in your unit tests and reuse it in other VMs.

Also, having a code behind IS NOT A BAD THING!

So, you rename your class by adding Service at the end, extract an interface for it and inject it in VM constructor using whatever dependency injection form you use.

Then in your button click command you can do:

var path = _systemDialogService.SelectFolder() - that's all

0
votes

A few years ago I wrote up a fairly detailed article showing how to do pure MVVM dialogs with data-binding, you might want to check out the sample project. In addition to the common system dialogs it also works fine with 3rd party dialog libraries.

I might be updating it soon actually, as I've recently implemented custom WPF dialog boxes (arbitrary shapes etc) which are similar but have a few quirks to you have to be mindful of.