wpf 在 MVVM Light 中使用参数打开新窗口的最佳实践

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14198443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 06:56:21  来源:igfitidea点击:

Best Practice to open a New Window in MVVM Light with Parameters

c#wpfmvvmmvvm-light

提问by Ian Overton

I am fairly new to mvvm and mvvm light, but I think I understand the general idea of it. What I don't understand is if I want to open a new window, but that window needs data from the caller what is the best practice to get that data to the new window? If I pass the data to the constructor then that means I need code in the code behind to pass it to the view model. I can't use messaging, because it isn't basic data.

我对 mvvm 和 mvvm light 还很陌生,但我想我了解它的总体思路。我不明白的是,如果我想打开一个新窗口,但该窗口需要来自调用者的数据,将这些数据传送到新窗口的最佳做法是什么?如果我将数据传递给构造函数,那么这意味着我需要后面的代码中的代码将其传递给视图模型。我不能使用消息传递,因为它不是基本数据。

采纳答案by Backlash

One popular choice is to use a service class that will create a view/viewmodel and display the new view. Your view model constructor and/or method/property could receive the data from the caller and then the view would be bound to the viewmodel prior to displaying it on the screen.

一种流行的选择是使用将创建视图/视图模型并显示新视图的服务类。您的视图模型构造函数和/或方法/属性可以从调用方接收数据,然后视图将在将其显示在屏幕上之前绑定到视图模型。

here is a very very simple implementation of a DialogService:

这是 DialogService 的一个非常简单的实现:

public class DialogService : IDisposable
{
    #region Member Variables
    private static volatile DialogService instance;
    private static object syncroot = new object();
    #endregion

    #region Ctr
    private DialogService()
    {

    }
    #endregion

    #region Public Methods
    public void ShowDialog(object _callerContentOne, object _callerContentTwo)
    {
        MyDialogViewModel viewmodel = new MyDialogViewModel(_callerContentOne, _callerContentTwo);
        MyDialogView view = new MyDialogView();
        view.DataContext = viewmodel;

        view.ShowDialog();
    }
    #endregion

    #region Private Methods

    #endregion

    #region Properties
    public DialogService Instance
    {
        get
        {
            if (instance == null)
            {
                lock (syncroot)
                {
                    if (instance == null)
                    {
                        instance = new DialogService();
                    }
                }
            }
            return instance;
        }
    }
    #endregion
}