Adding a ViewModelLocator and Merged Dictionaries to App.xaml

I guess this is one of these places where using Blend is an advantage… since I do these operations mostly with the help of the tool, the XAML is generated and I don’t need to think about it too much.

There is a trick when you add objects (for example Styles or a ViewModelLocator) to App.xaml when it already has merged resource dictionaries. The syntax is a bit convoluted, so here we go:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Skins/Brushes.xaml"/>
        </ResourceDictionary.MergedDictionaries>

        <vm:ViewModelLocator x:Key="Locator"
                                d:IsDataSource="True" />
    </ResourceDictionary>
</Application.Resources>

So yeah, the trick is to put the ViewModelLocator (or any other object for that matter) within the ResourceDictionary tag…

HTH,

Laurent

GalaSoft Laurent Bugnion

Print | posted on Tuesday, October 26, 2010 8:49 AM

Feedback

# re: Adding a ViewModelLocator and Merged Dictionaries to App.xaml

left by John Papa at 10/26/2010 9:36 AM Gravatar
I usually create a Resource Dictionary and name if ObjectResources.xaml. I put my ViewModelLocator in there along with any converters or other objects.

Either way is fine.

# re: Adding a ViewModelLocator and Merged Dictionaries to App.xaml

left by Laurent at 10/26/2010 9:57 AM Gravatar
Mmmh I saw that somewhere... Oh yeah it was in the code you sent me :-)

# re: Adding a ViewModelLocator and Merged Dictionaries to App.xaml

left by Bill Campbell at 10/26/2010 10:48 PM Gravatar
Cool! This is exactly what I was looking for. I'm using Blend as well but didn't realize that it would put it in the right place if added in Blend. I had added it in VS2010. Thanks!!

# re: Adding a ViewModelLocator and Merged Dictionaries to App.xaml

left by Gongdo at 2/9/2011 3:53 PM Gravatar
The reason why every DataSources(like ViewModelLocator) should be exposed in the App.xaml is, Blendability. Expression Blend doesn't show the DataSource's name which inside the MergedDictionaries on the Data Binding dialog.

Funny thing is, if you didn't expose the ViewModelLocator in the App.xaml and you declared it inside the ResourceDictionary(to reuse it), Blend(also Runtime) still works fine even though you cannot see the ViewModelLocator's name on the DataBinding dialog.

So, John Papa you're right. Either way works fine. However, for Blendability, you'd better get Laurent's one.

# re: Adding a ViewModelLocator and Merged Dictionaries to App.xaml

left by Brennt at 4/15/2011 8:18 PM Gravatar
Thanks for this solution. IMO ppl would be grateful if u put a comment line in App.xaml file of next MVVM Light build.
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: