I was looking for almost the exact same thing except for with a SaveFileDialog
. Here is what I came up with:
Create a message class with an Action<string>
property and a constructor with an Action<string>
argument.
public class SelectFolderMessage
{
public Action<string> CallBack {get;set;}
public SelectFolderMessage(Action<string> callback)
{
CallBack = callback;
}
}
In your ViewModel class, pass in a method or lambda expression when you call Messenger.Default.Send
. I set a property in my ViewModel class with the path returned by the view. I wrapped this inside the execute section of a RelayCommand
. I bound the RelayCommand
to a button in the view
...
new RelayCommand(() =>
{
Messenger.Default.Send(new SelectFolderMessage(
(pathfromview) => { viewmodelproperty = pathfromview;}));
})
In your view code behind, create a method to handle the message and register the handler with the messenger service. Don't forget to unregister if this is not your main window.
public MainWindow()
{
Messenger.Default.Register<SelectFolderMessage>(this, SelectFolderHandler);
}
private void SelectFolderHandler(SelectFolderMessage msg)
{
using (System.Windows.Forms.FolderBrowserDialog folderdialg = new System.Windows.Forms.FolderBrowserDialog())
{
folderdialg.ShowNewFolderButton = false;
folderdialg.RootFolder = Environment.SpecialFolder.MyComputer;
folderdialg.Description = "Load Images for the Game";
folderdialg.ShowDialog();
if (folderdialg.SelectedPath != null)
{
msg.CallBack(folderdialg.SelectedPath);
}
}
}
I came up with this idea reading Laurent Bugnion's Messenger article in MSDN Magazine: http://msdn.microsoft.com/en-us/magazine/jj694937.aspx