Silverlight tip #2: instantiating a new instance of a resource from code behind

I haven’t investigated this more in depth, but it seems to me that this is impossible:

this.Resources[“viewModel”] = new ViewModel();

At least it doesn’t work for me (actually I got a NotImplementedException), but it could be app specific. Anyway, this workaround strangely made it work:

ViewModel vm = this.Resources[“viewModel”] as ViewModel;
if (vm != null)
vm = new ViewModel();

I.e. creating a local object reference from the resource – casting it to the desired type – and afterwards instantiating a new object via the new reference.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com 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