Search code examples
c#wpfinstancesimpleioc

WPF MVVM How to create new Window instance with no input data


In WPF (MVVM) when I create new instance of window (view) it has no entry data - but when I enter some data, close window and reopen it contains the same data as window was closed with. How to provide "fresh" window (with blank fields which need to be fulfilled) instance each time?

I've tried many things and right now my class "ViewService" looks like this.

public class ViewService : IViewService
{
    public void Show<T>()
    {
        try
        {
            T window = Activator.CreateInstance<T>();
            var view = window as Window;
            view.Show();

        }
        catch (Exception)
        {
        }

    }

    public void ShowDialog<T>()
    {
        try
        {
            T window = Activator.CreateInstance<T>();
            var view = window as Window;
            view.ShowDialog();

        }
        catch (Exception)
        {
        }

    }

Thank you very much for your help.

PS. I use SimpleIoC container to register viewmodels.


Solution

  • Simpleioc will give you a singleton for any type and hence the same instance of a given viewmodel each time.

    Hence, your problem.

    Either.

    Use a different dependency injection system which is more sophisticated and will return a new instance each time.

    Or.

    Don't inject your window viewmodels at all.