ScottieA11
ScottieA11

Reputation: 3

How to stop more than one ViewModel from being created

I've started a project using MVVM Light and have run into an issue where once a window is created a ViewModel is bound to it, however, if I close this window and reopen the same window another viewmodel is made.

Through the debugger I can see the code looping through properties and methods after interacting with forms. I can see many instances of the same collections/properties/methods being fired. This then creates errors of 'Out of Bounds" after deleting items, etc.

*Note: Using ViewModelLocator, bound within XAML and completely removed from the XAML.cs files. ViewModels not referenced anywhere else.

I've attempted the following. No Help.

(WPF/MVVM) Single Instance In MainViewModel

How should I handle this to eliminate multiple ViewModels and looping properties/methods. Methods/properties should only be looped once.

EDIT

I've solved my issue. By referencing a static class within windows resources I was creating a new instance per ListView. Thus forcing the ViewModel to loop to conditions to meet those instances each form that consumed an instance.

By eliminating the resource and moving all data to MVVM Light DataService and using Task from System.Threading.Tasks, I am able to bind to a collection within the ViewModel rather than a independent instance. No more looping. Thanks for the answers.

Upvotes: 0

Views: 667

Answers (2)

Avinash Reddy
Avinash Reddy

Reputation: 937

You can always use Singleton Design Pattern

public sealed class Vm  
{  
    //Private Constructor.  
    private Vm()  
    {  
    }  
    private static Vm instance = null;  
    public static Vm Instance  
    {  
        get  
        {  
            if (instance == null)  
            {  
                instance = new Vm();  
            }  
            return instance;  
        }  
    }  
} 

Upvotes: 1

Andy
Andy

Reputation: 12276

It's common to use viewmodel first and a single window application rather than multiple windows with their own viewmodels.

Partly since it's quite easy for users to "lose" multiple windows. It also closes off a number of sharing issue edge cases where you have window X open and when you open window Y the processing clashes.

With what you have now, one simple way round this is to use SimpleIOC to provide your viewmodels.

SimpleIOC gives you singletons for anything you ask for.

You may have seen code does:

        SimpleIoc.Default.GetInstance<vmType>();

Which of course has a definite type inside those angle brackets.

An alternative is:

        SimpleIoc.Default.GetInstance(vmType);

Where vmType can be a variable. A Type variable which matches the tupe of the viewmodel you want.

You could make a markup extension which takes a type as parameter and makes that call, returning the viewmodel.

I've not tried it, but I don't think you even need to register the type using that syntax.

Upvotes: 1

Related Questions