WPF-MvvmLight NotificationMessageWithCallback示例?

时间:2015-03-13 12:05:40

标签: wpf mvvm-light messenger

是否有某个名为NotificationMessageWithCallback的MvvmLight功能的WPF样本?

我只想问一个简单的删除确认对话框。

由于

1 个答案:

答案 0 :(得分:2)

要将ViewModel中的值传递给View,首先要创建自定义Message 具有相关属性。我们继承NotificationMessageAction<MessageBoxResult>,如您所说,您想要一个确认框

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

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

在我们的ViewModel中,我针对被命中的命令(MyMessage)发送新的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);           
                                      }
              });
          }
     }
 }

最后,我们需要在后面的视图代码中注册消息

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);
           }