how to create multiple instance of model dynamically using servicelocator wpf

131 Views Asked by At

I have a tabcontrol in mainwindow.cs. I want to add new tab dynamically and each tab has its own unique viewmodel instance. I have managed to do it for one tab. But when I create the second one it has the same instance of the model. I am doing with a viewmodelLocator. Here is my code in ViewModelLocator:

for (int i = 0; i <= 2; i++)
{
    locatorProvider.Register<IXmlParser>(() => new XmlParser(), key);
    locatorProvider.Register<IFileHandler>(() => new FileHandler(), key);
    locatorProvider.Register<ISetHandler>(() => new SetHandler(), key);
    locatorProvider.Register<RegisterViewModel>();
}

and I try to retrieve it with this piece of code.

RegisterViewModel registerViewModel = SimpleIoc.Default.GetInstance(key);

1

There are 1 best solutions below

0
Mikias Gebre On

Maybe it might help someone in the future when working with multiple instance of the same viewmodel. Anyway here is the answer. So I register the interface as I did earlier but when I register the viewModel I pass all of the three interface with the corresponding key with it.

// Helper classes

locatorProvider.Register(() => new XmlParser(), key); locatorProvider.Register(() => new FileHandler(), key); locatorProvider.Register(() => new SetHandler(), key);

// Register view models

locatorProvider.Register(() => new > >RegisterViewModel(locatorProvider.GetInstance(key), locatorProvider.GetInstance(key), locatorProvider.GetInstance(key)), key);