0

In my application I use multiple windows that have the same view-viewmodel pair. Also I use a unity container.

I recently added a translation module, WPF Localization Using RESX Files by Grant Frisken (code project). Now if I change the language, the constructor of the viewmodel is executed again, and no variables are stored. The view has still its datacontext set to some instance of that viewmodel but all the views then are using the same viewmodel.

Currently I think I use a wrong approach, but what would be a better solution?

Opening a new window:

    var openWindow = new MyView();
    openWindow.Show();

In my xaml:

    DataContext="{Binding MyViewModel, Source={StaticResource Locator}}" 

In my viewmodel

    private IMyWindowData _data;

    [InjectionConstructor]
    protected SettingsBaseViewModel(IMyWindowData data)
    {                        
        _data = windows;
    }

This all worked fine until I implemented the new language module. The variable _data is gone when I choose to change language. The injection constructor then has the data of other windows that also are of the same type.

I desperately searched the internet for this but didn't succeed finding an answer.

BoboProg
  • 121
  • 1
  • 1
  • 8

1 Answers1

2

I found a solution for my problem. After reading Laurent Bugnion his post about this. In my projects I use his mvvm light framework with the viewmodelLocater which can be instantiated indefinitely.

    DataContext = ((ViewModelLocator)Application.Current.Resources["Locator"])
    .WindowData(Guid.NewGuid);

Is placed in the backend of each View. Once the View is closed the garbage collector will automatically collect the ViewModel.

    public DataModel WindowData(Guid uniqueId)
    {
        return BootStrapper.Container.Resolve<DataModel>(uniqueId.ToString());
    }

The unity container instantiates a new object each time a different name is created.

Community
  • 1
  • 1
BoboProg
  • 121
  • 1
  • 1
  • 8