MVVM ViewModel and static methods
c#, mvvm, static, wpf
Solution
How to display dialogs is one of the areas of MVVM that is not immediately clear, and there are a number of ways the behaviour can be achieved.
I would suggest using either a mediator (as described here) or by injecting a dependency on the view model that controls dialogs:
interface IDialogService
{
void ShowRelatedDocumentsA(A a);
}
...
class MyViewModel
{
private IDialogService _dialogService
public MyViewModel(IDialogService dialogService) { _dialogService = dialogService; }
public void DoSomething()
{
_dialogService.ShowDialog(...);
}
}
Either of these can will permit you to control the creation of the view outside of the view model, and will remove any explicit references from VM -> V.
Problem
I try to rewrite my Application using the MVVM pattern. I have a window to show related documents for different objects with static methods like this: ``` public partial class ShowRelatedDocuments : Window { private ShowRelatedDocuments() { InitializeComponent(); } public static void ShowRelatedDocument(A objA) { ShowRelatedDocuments srd = new ShowRelatedDocuments(); srd.HandleA(objA); srd.ShowDialog(); } public static void ShowRelatedDocument(B objB) { ShowRelatedDocuments srd = new ShowRelatedDocuments(); srd.HandleB(objB); srd.ShowDialog(); }} ``` Is there a way to keep these methods static like this? ``` ShowRelatedDocumentsVM.ShowRelatedDocument(A objA); ShowRelatedDocumentsVM.ShowRelatedDocument(B objB); ``` I didn't find anything about ViewModels and static methods. Can a VM create a instance of itself and show his View (here a window)? Or is the better way to pass the objects as parameter to the constructor of the VM like this? ``` public ShowRelatedDocumentsVM(A objA) { HandleA(obj A) ShowRelatedDocuments srd = new ShowRelatedDocuments(); srd.DataContext = this; srd.ShowDialog(); } public ShowRelatedDocumentsVM(B objB) { HandleB(objB); ShowRelatedDocuments srd = new ShowRelatedDocuments(); srd.DataContext = this; srd.ShowDialog(); } ``` Or are both ways wrong, cause i breach the MVVM pattern due creating the view in the viewmodel? Thx in advance.