Using UserControl.Loaded event with PRISM IActiveAware

I found this subtle behavior while implementing IActiveAware on my Views using PRISM 4.0.

As a standard practice, I would always set the DataContext on the Loaded event of my views i.e. this.Loaded += (s,e) => new ViewModel(). Now without PRISM it was working fine, but when trying to make my ViewModel IActiveAware, it didn’t behave as expected. It would not invoke the IActiveAware member methods. I found that if i made my view IActiveAware, the view would work fine and behave properly as IActiveAware.

Finally, i realised that because I am setting the DataContext on Loaded event, it must be null at the time when PRISM is doing its plumbing and initializations. So instead of setting the DataContext on Loaded event, i just set it in the constructor and immediately my ViewModel became IActiveAware. So those who are having the same issue, should take note of this and not set DataContext on loaded event unless you don’t mind making your view IActiveAware and writing code in the codebehind.

Have a good day!

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s