Pop Display Alert/ Message from ViewModel

Guys.

How do i invoke/ call display alert/show message once my program did some logic in ViewModel (MVVM)?

E.g

  1. Login Form --> Enter Login Data ---> Click Login Button---> Bind button command to LoginViewModel

Lets say the program done the login validation..how do i send back the login result to Login Page (assuming if login failed) ?

Posts

  • TorbenKruseTorbenKruse DEMember ✭✭✭

    @KentLiaw
    For displaying dialogs from the ViewModel I use Acr.UserDialogs
    For doing navigation, like popping the login page, I pass the Navigation object from the Page to my ViewModel once I create it.

  • arroyosarroyos MYMember

    Thanks @TorbenKruse for the suggestions. Will check on the acr.userdialogs.

    Currrently looking at messaging center.

    Any idea which better way to do this ?

  • NMackayNMackay GBInsider, University mod
    edited August 2015

    You can just write a dialog service like this one in MVVM light and call the alert from your VM.

    http://mvvmlight.codeplex.com/SourceControl/latest#Samples/Flowers/Flowers.Forms/Flowers.Forms/Helpers/DialogService.cs

    Then in your VM you can get call the dialog service.

            var dialog = ServiceLocator.Current.GetInstance<IDialogService>();
            await dialog.ShowMessageBox(ResourceConstants.CommonAddressUnavailable,
                        ResourceConstants.PopupDialogGeneralInfo);
    

    Just remember to register the dialog service in your IoC in the app startup

                // Setup dialog service
                var dialog = new DialogService();
                SimpleIoc.Default.Register<IDialogService>(() => dialog);
    
                // Setup exception service
                var ex = new ExceptionService();
                SimpleIoc.Default.Register<IExceptionService>(() => ex);
    
                // setup setting service
                var setting = new SettingService();
                SimpleIoc.Default.Register<ISettingService>(() => setting);
    
                etc
    
    

    PM me and I'll send you a sample app on how to do this.

  • DaniSchmidDaniSchmid CHMember ✭✭

    Hei @NMackay
    That Implementation uses
    public void Initialize(Page dialogPage)

    The Initialize Method is never called in my instance. And therefor the dialogPage remains NULL leading to nullpointer refs.
    Any Idea?

  • NMackayNMackay GBInsider, University mod
    edited September 2015

    @DaniSchmid

    It works fine for me, I have a working sample of an MVVM Light app with dialog callback, viewmodels, binding etc.

    If you want a copy then PM me in the next hour and I'll upload the sample for you. Or I'll be in tomorrow morning for a few hours.

  • NMackayNMackay GBInsider, University mod

    @DaniSchmid

    Replied to your PM.

  • yammak2004yammak2004 USMember ✭✭

    @NMackay I was wondering if I could take a look at your sample?

  • JimTyminskiJimTyminski USUniversity ✭✭

    Why not post it? Please? :)

    @NMackay said:
    @DaniSchmid

    It works fine for me, I have a working sample of an MVVM Light app with dialog callback, viewmodels, binding etc.

    If you want a copy then PM me in the next hour and I'll upload the sample for you. Or I'll be in tomorrow morning for a few hours.

  • NMackayNMackay GBInsider, University mod

    @JimTyminski

    I just don't like posting links to my G drive publicly. I'll post the code on github at some stage so anyone can take a look at it's nothing fancy.

    In the interim, just PM me if you want a link.

    Thanks.

  • joilson.cisnejoilson.cisne BRMember ✭✭

    @DaniSchmid said:
    Hei @NMackay
    That Implementation uses
    public void Initialize(Page dialogPage)

    The Initialize Method is never called in my instance. And therefor the dialogPage remains NULL leading to nullpointer refs.
    Any Idea?

    Hey @DaniSchmid Did figure out where to call the Initialize method?

  • NMackayNMackay GBInsider, University mod

    @joilson.cisne

    Send you a PM.

  • RHudsonRHudson CAMember ✭✭✭

    I use FreshMVVM which will display an alert from the VM

    CoreMethods.DisplayAlert ("Goodbye World", "", "Ok");

  • TonyMelonyTonyMelony USMember

    Not very helpful guys. Can somebody post an example?

  • LucioMSPLucioMSP MXUniversity ✭✭✭

    App.NotificationService.ShowAlert("Message");

  • Can you please some sample for showing the alert from view model

  • MickGeorgeMickGeorge USMember ✭✭

    I use Prism https://github.com/PrismLibrary/Prism-Samples-Forms for MVVM and the IPageDialogService will be what you want to implement.

  • JesseLibertyJesseLiberty USInsider, University ✭✭✭

    @NMackay Forgive me if you've answered this already. I have MVVM light. I need to create a message from my VM to put up a dialog box that will request a yes or no response, and then get that back in the calling method in the VM.

    That is, someone clicks on a button, my command binds to a method in the VM. In that method I want to say "are you sure? yes/no" and get back an answer before proceeding.

    Thanks!

  • NMackayNMackay GBInsider, University mod

    @JesseLiberty

    Hi jesse,

    You just get an action back so you could handle it in a lambda or do it like this.

     public RelayCommand ConfirmCommand
            {
                get
                {
                    return _confirmCommand
                           ?? (_confirmCommand = new RelayCommand (
                               async () =>
                               {
                                   try
                                   {
                                       await _dialogService.ShowMessage("Does dialog callback work in MVVM Light",
                                          "Callback Test",
                                          "Yup",
                                          "Nope",
                                          DialogAction);   
                                   }
                                   catch (Exception ex)
                                   {
                                       var res =_dialogService.ShowMessage(ex.Message.ToString(),
                                           ResourceConstants.PopupDialogGeneralError,
                                           ResourceConstants.PopupDialogOkButton,
                                           null);
                                   }
                               }));
                }
            }
    
            private async void DialogAction(bool value)
            {
                try
                {
                    await _dialogService.ShowMessage("Result: " + value,
                                          "Result",
                                          ResourceConstants.PopupDialogOkButton,
                                          null);
                }
                catch (Exception ex)
                {
                    var res = _dialogService.ShowMessage(ex.Message.ToString(),
                                           ResourceConstants.PopupDialogGeneralError,
                                           ResourceConstants.PopupDialogOkButton,
                                           null);
                }
            }
    
  • NMackayNMackay GBInsider, University mod

    I just inject in the MVVM Light dialog service.

    public class StartViewModel : ViewModelBase, ICleanup
        {
            // Services
            private readonly IDialogService _dialogService;
            private readonly INavService _navService;
            private readonly IOrderService _ordService;
    
            // Commands
            private RelayCommand<Order> _selectCommand;
            private RelayCommand _confirmCommand;
            private RelayCommand _refreshCommand;
            private RelayCommand _updateUiCommand;
    
            public StartViewModel(IOrderService ordServ, INavService nav, IDialogService dialog)
            {
                _ordService = ordServ;
                _navService = nav;
                _dialogService = dialog;
    
                Messenger.Default.Register<ClearOrderMessage>(this, action =>
                {
                    Orders = new ObservableCollection<Order>();
                });
            }
    
  • MelDeSoysaMelDeSoysa USMember
    edited July 2017

    @NMackay, if I just want to get the bool result from the alert, can I just use the code below directly from the vm instead of using the dialog service?

        var result = await Application.Current.MainPage.DisplayAlert(
                title,
                message,
                buttonConfirmText,
                buttonCancelText);
    
  • NMackayNMackay GBInsider, University mod
    edited December 2017

    @MelDeSoysa said:
    @NMackay, if I just want to get the bool result from the alert, can I just use the code below directly from the vm instead of using the dialog service?

      var result = await Application.Current.MainPage.DisplayAlert(
                title,
                message,
                buttonConfirmText,
                buttonCancelText);
    

    Yes but then you are tightly coupling the viewmodel to the UX layer, the idea of the interface is to abstract away the actual device implementation of the dialog. Essentially the viewmodel should have no idea of the UI layer, having properties that are UIElements like visibility in the VM tightly couples both.

    It's not perfect and in mobile you have to implement certain device features in the VM sometimes but you can abstract that away.

  • ehainesehaines Member ✭✭

    I did something like this following an event handler pattern to fire a listening method in the page from the view model.

    Further reading on C# events and the Observer Pattern:

    http://blog.adamkemp.com/2015/03/decoupling-views.html

  • NMackayNMackay GBInsider, University mod

    @ellahaines said:
    I did something like this following an event handler pattern to fire a listening method in the page from the view model.

    Further reading on C# events and the Observer Pattern:

    http://blog.adamkemp.com/2015/03/decoupling-views.html

    An excellent blog post that.

  • jcpc91jcpc91 Member

    Need help
    Im using the library mvvmlightlibs inside there is a class "DialogService" implements the interface "IDialogService" when i run the app on an android i get null reference in this line

    var builder = new AlertDialog.Builder(ActivityBase.CurrentActivity);

    the ActivityBase.CurrentActivity is null

    someone knows what's happening

Sign In or Register to comment.