0

Is there a WPF sample of MvvmLight feature called NotificationMessageWithCallback somewhere?

I just want to ask a simple delete confirmation dialog.

Thanks

emoreau99
  • 634
  • 6
  • 16
  • I was probably on the wrong track. It seems that I can simply use NotificationMessageAction [link](http://stackoverflow.com/questions/6440492/how-to-receive-dialogresult-using-mvvm-light-messenger). I can get it to work. One question still: how to pass arguments? For example, how could my ViewModel pass a value when sending the message that would be shown in my MessageBox? – emoreau99 Mar 13 '15 at 13:48
  • In the link you mentioned you would add a property to the ShowPasswordMessage. – SWilko Mar 16 '15 at 08:55
  • And how will the VM provide a value through the NotificationMessageAction to the view? – emoreau99 Mar 16 '15 at 18:13

1 Answers1

2

To pass a value from a ViewModel to a View firstly create a custom Message with relevant properties. We inherit from NotificationMessageAction<MessageBoxResult> as you mentioned you wanted a confirmation box

public class MyMessage : NotificationMessageAction<MessageBoxResult>
{
    public string MyProperty { get; set; }

    public MyMessage(object sender, string notification, Action<MessageBoxResult> callback) :
        base (sender, notification, callback)
    {
    }
}

In our ViewModel I send a new MyMessage on a command being hit (SomeCommand)

public class MyViewModel : ViewModelBase
{
     public RelayCommand SomeCommand
     {
          get
          {
              return new RelayCommand(() =>
              { 
                  var msg = new MyMessage(this, "Delete", (result) =>
                            {
                               //result holds the users input from delete dialog box
                               if (result == MessageBoxResult.Ok)
                               {
                                   //delete from viewmodel
                               }
                            }) { MyProperty = "some value to pass to view" };

                  //send the message
                  Messenger.Default.Send(msg);           
                                      }
              });
          }
     }
 }

Finally we need to Register the message in the view code behind

public partial class MainWindow : Window
{
     private string myOtherProperty;

     public MainWindow()
     {
          InitializeComponent();

          Messenger.Default.Register<MyMessage>(this, (msg) =>
           {
               myOtherProperty = msg.MyProperty;
               var result = MessageBox.Show("Are you sure you want to delete?", "Delete", MessageBoxButton.OKCancel);
               msg.Execute(result);
           } 
SWilko
  • 3,542
  • 1
  • 16
  • 26