c# - MVVM ViewModel 和静态方法

标签 c# wpf mvvm static

我尝试使用 MVVM 模式重写我的应用程序。

我有一个窗口来显示不同对象的相关文档,静态方法如下:

    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();
    }}

有没有办法让这些方法像这样保持静态?

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

我没有找到任何关于 ViewModel 和静态方法的信息。 VM 可以创建自己的实例并显示他的 View (这里是一个窗口)吗?

或者像这样将对象作为参数传递给 VM 的构造函数是更好的方法吗?

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();
}

或者两种方式都错了,因为我在 View 模型中创建 View 而违反了 MVVM 模式?

提前致谢。

最佳答案

如何显示对话框是 MVVM 中尚不清楚的领域之一,可以通过多种方式实现该行为。

我建议使用调解器(如 here 所述)或在控制对话框的 View 模型上注入(inject)依赖项:

interface IDialogService
{
    void ShowRelatedDocumentsA(A a);
}

...

class MyViewModel
{
    private IDialogService _dialogService

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

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

其中任何一个都允许您控制 View 模型之外的 View 的创建,并将从 VM -> V 中删除任何显式引用。

关于c# - MVVM ViewModel 和静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4023119/

相关文章:

asp.net - Azure 可以运行 WPF 吗?

Xaml 两种方式将文本框绑定(bind)到可观察集合

c# - 在另一个 ViewModel 中完成数据库更改后,如何 "refresh"我的 ViewModels?

c# - 如何从我的 asp.net 应用程序注销用户?

c# - iOS Row Selected 未被调用

c# - 关闭 C# WPF 应用程序中的所有 Windows

wpf - App 对象中的 Log4Net?

android - 将MutableLiveData传递给其他ViewModel是否有效?

c# - 启动 ConfigureServices AddMvc() 中的 KeyNotFoundException

C# 相当于 C (WinAPI) 中的 DllMain