Xaphann
Xaphann

Reputation: 3677

WPF Global Class MVVM

In trying to setup a global class in App.xaml;

<Application.Resources>
    <local:MySettingsClass x:Key="GlobalSettings" />
    <ResourceDictionary >
        <!-- My Resources -->
    </ResourceDictionary >
</Application.Resources>

Although I am getting an error message of

Each dictionary entry must have an associated key.

and

'App' does not contain a definition for 'InitializeComponent' and no extension method 'InitializeComponent' accepting a first argument of type 'App' could be found (are you missing a using directive or an assembly reference?)

Now I can go in and and an x:Key to ResourceDictionary but I have never seen anyone do that, so that seems wrong. The second error message leads me to believe that I am doing this wrong.

Do I have the wrong solution for this problem or is something simple I am missing?

Upvotes: 1

Views: 297

Answers (1)

Application.Resources IS a resource dictionary, implicitly. You could just slap resources right in there. This would be valid:

<Application.Resources>
    <local:MySettingsClass x:Key="GlobalSettings" />
    <!-- Pretty much anything with an x:Key attribute. -->
</Application.Resources>

But if you're merging dictionaries you do need the explicit <ResourceDictionary> tag, and usually in App.xaml you're merging dictionaries.

The problem you ran into is that in your XAML, the first thing it sees is your GlobalSettings resource, before anything. That's the first thing it sees, so it figures OK, he's just slapping some resources in here. It creates a ResourceDictionary and proceeds to add everything it sees to that. Next thing it sees is <ResourceDictionary>, and it thinks you're trying to add another resource dictionary to the first one as a resource, but without an x:Key attribute. I tried just now and it did let me add one with x:Key, not that I know of any reason to do that. It didn't merge the resources into the outer one.

Try this:

<Application.Resources>
    <ResourceDictionary>
        <!-- One of My Resources -->
        <local:MySettingsClass x:Key="GlobalSettings" />

        <!-- My Other Resources -->

        <ResourceDictionary.MergedDictionaries>
            <!-- Merged dictionaries -->
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

If you keep getting the InitializeComponent error, please share your code for App.xaml.cs

Upvotes: 3

Related Questions