This project has moved and is read-only. For the latest updates, please go here.

Multiple ViewModels getting created

Feb 2, 2011 at 6:08 AM


I am specifically instantiating my ViewModel in Code, so that i can pass parameters to it and Dispose it. However my XAML needs to make use of the EventToCommand Behaviour for a ListView context menu.
Creating the EventToCommand behaviour requires a static resource of the type of my viewmodel resulting in creation of another duplicate ViewModel from XAML.

This is causing erratic behaviour in the app as both the view models are now registering and listening to messages being sent by popups etc.

<i:Interaction.Triggers><i:EventTrigger EventName
<GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding ShowProgramDetailsCommand, Mode=OneWay, Source={StaticResource ProgramListViewModelDataSource}}" CommandParameter="{Binding}"/>
I don't want to use a Singleton ViewModel as i want a new ViewModel to be generated each time i come to the view.

Many time for the EventToCommand behaviour we do not have to specify the Source( like in buttons etc) , but in this case the Event to command behaviour is on the context menu of the ListView defined as a grid view and it doesn't work without specifying the source....


I can do workarounds in the code and safeguard my functionality but how do i ensure the VM created via XAML will stop listening for events and will get disposed on its own?

Please guide!



Feb 2, 2011 at 6:55 AM


You should use ViewModelLocator - the ViewModel will be set (as DataContext for whole view) only on XAML. If you want pass arguments to ViewModel good start would be using Messaging. On view closing you should call viewModel's Cleanup (via messaging or directly through dataContext) method, in order to unsubscribe to Messaging.

This functionality isn't out of the box, only pieces for it are ready to use.


Aurimas Neverauskas