MVVM ViewModel and Static Methods

I am trying to rewrite my application using the MVVM pattern.

I have a window for displaying related documents for different objects with static methods, such as:

    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 like this?

ShowRelatedDocumentsVM.ShowRelatedDocument(A objA);
ShowRelatedDocumentsVM.ShowRelatedDocument(B objB);

I did not find anything about ViewModels and static methods. Can a VM create an instance of itself and show its appearance (here is a window)?

Or is the best way to pass objects as a parameter to a virtual machine constructor as follows?

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 both ways are wrong, cause a violation of the MVVM template due to the creation of a view in the viewmodel?

thanks in advance.

+3
source share
1 answer

- MVVM, , .

( ), , :

interface IDialogService
{
    void ShowRelatedDocumentsA(A a);
}

...

class MyViewModel
{
    private IDialogService _dialogService

    public MyViewModel(IDialogService dialogService) { _dialogService = dialogService; }

    public void DoSomething()
    {
        _dialogService.ShowDialog(...);
    }
}

VM → V.

+2

Source: https://habr.com/ru/post/1771482/


All Articles