Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include two resources in Page.Resources?

Tags:

c#

wpf

xaml

In WPF, this used to work fine:

<Page.Resources>
    <ResourceDictionary Source="resources/Styles.xaml" />
</Page.Resources>

but adding a converter (see below) causes an error on the 2nd resource (Style.xaml): Each dictionary entry must have an associated key.

<Page.Resources>
    <local:MySizeConverter x:Key="sizeConverter"/>
    <ResourceDictionary Source="resources/Styles.xaml" />
</Page.Resources>

However, adding a key to the 2nd line (e.g. <ResourceDictionary x:Key="myStyleDict" Source="resources/Styles.xaml" /> causes the following error in code behind

The name 'aTextBlockUsedToWork' does not exist in the current context

where aTextBlockUsedToWork could be successfully accessed in code behind before adding the key. Note that the converter works fine if I comment out the style resource. How can I have both of the resources working?

like image 278
totoro Avatar asked Oct 21 '14 06:10

totoro


People also ask

How do you add a resource to a dictionary?

Tip You can create a resource dictionary file in Microsoft Visual Studio by using the Add > New Item… > Resource Dictionary option from the Project menu. Here, you define a resource dictionary in a separate XAML file called Dictionary1.

How do I add a resource to a project in WPF?

To add a Resource Dictionary into your WPF application, right click the WPF project > add a Resource Dictionary. Now apply the resource "myAnotherBackgroundColor" to button background and observe the changes.

What is static and dynamic resources?

Static Resources retrieved once by referencing element and used for the lifetime of the resources. Whereas, DynamicResources retrieve every time they are used. The downside of Dynamic resources is that they tend to decrease application performance.

What can we store in a ResourceDictionary?

In Extensible Application Markup Language (XAML), the ResourceDictionary class is typically an implicit collection element that is the object element value of several Resources properties, when given in property element syntax. For details on implicit collections in XAML, see XAML Syntax Terminology.


1 Answers

You need to use MergedDictionaries to import another dictionary file, like this:

<Page.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="resources/Styles.xaml" />
        </ResourceDictionary.MergedDictionaries>
        <local:MySizeConverter x:Key="sizeConverter"/>
    </ResourceDictionary>
</Page.Resources>
like image 74
Yogesh Avatar answered Oct 21 '22 12:10

Yogesh