Open a dialog from VM using Events

This is a quick summary of how I open a dialog box from the view model. There are other ways to do this (as noted in previous postings), but this is easy, easy to maintain and puts most of the logic in the view model.

In ViewModel I have

    public ICommand ShowInfoCommand =>
        new Command(() => OnShowInfo());  

In the OnBlindCalibrationInfo (in view model) I have this:

    public Action AskForInformation { get; set; }
    private void OnShowInfo()
    {
        AskForInformation?.Invoke();
    }

Then in the code behind constructor, I have:

        _viewModel.AskForInformation = async () =>
        {
            await UserDialogs.Instance.AlertAsync(new AlertConfig
            {
                Title = AppConstants.AskForInfoHeader,
                Message = 
                   AppConstants.AskForInfoHeaderText
            });
        };

That’s it. Easy peasy.

  1. Declare the command as normal, pointing to a method
  2. Declare a property of type Action
  3. In the method, check to see if the Action is null, if not Invoke it (it will be null if noone registers for it; much like OnPropertyNotifyChanged)
  4. In the code behind you set that Action to pop your dialog box.

What you get is a very pretty dialog box. Note: I left out the OK and Cancel button, which means it will default to just OK.

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen Pluralsight & LinkedIn Learning courses. He was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Xamarin Certified Mobile Developer and a Xamarin MVP and a Microsoft MVP.
This entry was posted in .NET Core, C# 8 and tagged . Bookmark the permalink.