Question

I need the result of FolderBrowserDialog in my view-model,

CodeBehind.cs

 private static void SelectFolderDialog()
    {
        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)
            {
                var notifypath = new GenericMessage<string>(folderdialg.SelectedPath);
                Messenger.Default.Send(notifypath);

            }
        }

What i'm planning is , From View-model send a notification with callback to view , executing the FolderBrowserDialog return the Selected path back to the view model.

How do i send notificationmessage with callback / NotificationWithAction using MVVM-Light . please help me with a sample as I'm new to Wpf and MVVM-Light.

Any Help is appreciated

Était-ce utile?

La solution

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top