In this post I would like to propose a simple solution for DialogMessaging on the UI using MVVM Light Toolkit.
The idea is to use the power of IOC pattern included in the MVVM Light Tookit available free from NuGet.
First of all we need an Interface that allows to define the support to DialogMessaging.
Here an example:
public interface IDialogMessageService
{
Task ShowAsync(string title, string message);
Task ShowAsync(string title, string message, IEnumerable commands);
}
Now we have to move to the implementation:
public class DialogMessageService: IDialogMessageService
{
public async Task ShowAsync(string title, string message)
{
await ShowAsync(title, message, null);
}
public async Task ShowAsync(string title, string message, IEnumerable commands)
{
var messageDialog = new MessageDialog(message, title);
if(commands != null)
{
foreach(var command in commands)
messageDialog.Commands(command);
}
await messageDialog.ShowAsync();
}
}
And then, we need to register this service when the app starts.
So, define the following method in the ViewModelLocator class:
public class ViewModelLocator
{
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
if (!ViewModelBase.IsInDesignModeStatic)
{
Registers();
}
}
public void Registers()
{
SimpleIoc.Default.Register<IDialogMessageService, DialogMessageService>();
}
}
In the viewmodel, where we need the DialogMessageService we use dependency injection in this way:
public class MainViewModel: ViewModelBase
{
public ICommand ShowMessageCommand{ get; private set;}
public MainViewModel(IDialogMessageService dialogMessageService)
{
this.ShowMessageCommand = new RelayCommand( async() =>
{
await dialogMessageService.ShowAsync("Title", "Hello", null);
});
}
}
And at the end we can use the communication from View - ViewModel with MVVM Design Pattern simply. 🙂
Enjoy
Maurizio



























