Unkeyed DataTemplate Resolution Issue


Hello Everyone!

So recently i have been playing around with dynamically injecting a ResourceDictionary that contains an Unkeyed DataTemplate into the Resource Lookup Tree before the Generic.xaml that contains the default DataTemplate targetting the same type.  One would think that if a loaded ContentControl whose Content is an instance of an object that is the same type as the DataTemplate that the UI would find the newly resolved DataTemplate and switch the UI.  I have found that this does not work.  You can do the same thing with a Style and it will properly flip the UI to the definition of the newly injected Style, but not for a DataTemplate.

So the question becomes, how can we provide this setup?  What im going to do today is show you how you can setup your ContentControl to support this functionality!

So the first thing we are going to do is go ahead and give our DataTemplate a Key.

<DataTemplate DataType="{x:Type ssVms:SlideShowViewModel}"
              x:Key="SlideShowViewModelDataTemplate">

Next we are going to bind our ContentControls ContentTemplate property as a “Dynamic” resource as such.

<ContentControl x:Name="SlideShowViewModelHost"
                ContentTemplate="{DynamicResource SlideShowViewModelDataTemplate}"/>

Now the DynamicResource is the key here.  Becuase it is explicitly set as a DynamicResource it causes more evaluation of found resources causing it to be invalidated when you inject a new ResourceDictionary.  Now that we have this we can swap out ResourceDictionaries containing new DataTemplates for our objects and have the UI automatically flip to the new visuals!

Hope this helps anyone else running into this same issue.  Have a good day!

Comments are closed.