0

在某处是否有名为 NotificationMessageWithCallback 的 MvvmLight 功能的 WPF 示例?

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

谢谢

4

1 回答 1

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);
           } 
于 2015-03-16T21:15:01.197 回答