0

In a ViewModel I have a Command, and in a View I have a button binded to that Command :

...
public Command SaveCommand { get;  }

private async void Save(){
  IsBusy = true;
            Estatus = "Grabando...";
            Task<bool> taskSaved = _negotiationRepo.SaveNegotiation(_negotiation, _following);
            bool Saved = await taskSaved;
            IsBusy = false;
            if (Saved)
            {
                Estatus = "Saved";
                await Application.Current.MainPage.DisplayAlert("Negotiation","Saved correctly","OK");
            }
            else
            {
                await Application.Current.MainPage.DisplayAlert("Negotiation", "Problem saving negotiation", "OK");
            }
}

public NegotiationVM(Client client){
...
  SaveCommand = new Command((Save),canExecute: ()=>!IsBusy);
...
}

In XAML View:

<Button Text="Save" BackgroundColor="#3276b1"  TextColor="White" Command="{Binding SaveCommand}">

As you can see, I have a DisplayAlert in this ViewModel class. I'm not sure, but according to MVVM I shouldn't do this here, or at least not in that way. How can I properly display an alert or prompt after this command is fired?

I'm not using any MVVM Framework at this moment, most examples are focused in MVVM Light or Prism.

Mr_LinDowsMac
  • 2,444
  • 7
  • 50
  • 74
  • 2
    Sort of related: https://stackoverflow.com/questions/14297312/wpf-messagebox-with-mvvm-pattern – user6144226 Jul 07 '17 at 16:40
  • Not sort-of-related, it's absolutely how you should handle this type of thing in MVVM, with a good code sample. –  Jul 07 '17 at 16:48
  • @Will Why is marked as duplicate? This is for Xamarin.Forms not WPF. Even if is similar, not equal functions and implementations. – Mr_LinDowsMac Jul 07 '17 at 17:01
  • I don't know xamarin, so I don't know if they have a built-in mechanism for this, so reopened. If they *don't*, that dupe has your answer. Nothing about xamarin prevents you from defining an interface to model interactions with a dialog, then implement that in your UI and pass the implementation into your view model. –  Jul 07 '17 at 18:13

1 Answers1

-1

What I tend to do is have my code behind (yes you can do that) hook into the event and have it display the message. This is also vitally important if the command handler needs to await and operation and it is more intuitive to caputure the UI context in the UI callback rather than in the model callback

MickyD
  • 14,343
  • 6
  • 43
  • 67