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

╄→гoц情女王★ 提交于 2019-12-18 22:33:01

问题


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.


回答1:


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:

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
}


来源:https://stackoverflow.com/questions/14198443/best-practice-to-open-a-new-window-in-mvvm-light-with-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!