I am developing a WPF 4.0 - MVVM application based on PRISM framework (Unity Container).
I was wondering what is the best way to implement dialogs in the mvvm pattern. I am planning to use quite a few in my application so I want something reusable.
Yes, it is possible and I was able to do that because class DialogFragment extends Fragment. So I added a view model just like any other fragment.
To create a new dialog box In Resource View, right-click your . rc file and select Add Resource. In the Add Resource dialog box, select Dialog in the Resource Type list, then choose New. If a plus sign (+) appears next to the Dialog resource type, it means that dialog box templates are available.
AlertDialog is a lightweight version of a Dialog. This is supposed to deal with INFORMATIVE matters only, That's the reason why complex interactions with the user are limited. Dialog on the other hand is able to do even more complex things .
Getting Started. Open Android Studio and import the starter project. Create a new class CustomDialog. kt to contain our dialog.
Since you are using Prism/Unity implement the mediator pattern for your View Models.
ViewModels now use the IDialogService to show the required dialog.
public interface IDialogService
{
void RegisterDialog (string dialogID, Type type);
bool? ShowDialog (string dialogID);
}
public class DialogService : IDialogService
{
private IUnityContainer m_unityContainer;
private DialogServiceRegistry m_dialogServiceRegistry;
public DialogService(IUnityContainer unityContainer)
{
m_unityContainer = unityContainer;
m_dialogServiceRegistry = new DialogServiceRegistry();
}
public void RegisterDialog(string dialogID, Type type)
{
m_dialogServiceRegistry.RegisterDialog(dialogID, type);
}
public bool? ShowDialog(string dialogID)
{
Type type = m_dialogServiceRegistry[dialogID];
Window window = m_unityContainer.Resolve(type) as Window;
bool? dialogResult = window.ShowDialog();
return dialogResult;
}
}
If you use ViewModel events & handlers in the View, use the WeakEventHandler pattern to eliminate a potential resource leak. Also, it is possible for multiple Views to be attached to the same ViewModel. I've worked on projects with one ViewModel -> one View. But also one ViewModel -> multiple Views. Just something to consider when making your design decisions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With