开发者

How do I use global resources in WPF?

I have a WPF application which I would like to use some static resources in. I have created a Resource Library XAML file which contains a resource. I have also added a string into the Resources of the project through th开发者_StackOverflow社区e Properties panel.

I assumed I could just use these resources with the binding expression:

{StaticResource ResourceName}

But visual studio is telling me the resources are not found. Do I have to include some form of reference in my XAML? The examples I have seen only include resources locally such as:

<Window.Resources>, <Page.Resources> etc

I don't want to include the resources locally because I want them to be available to multiple parts of the application.


Put them in the App.xaml :)

In each WPF application there is an App.xaml (and its corresponding code file, App.xaml.cs or App.xaml.vb) which works as a global file for application wide declarations. You can use this file to declare a constant look and feel across your application. For example you can declare a default red background for all buttons in an application.

http://www.microsoft.com/emea/msdn/thepanel/en/articles/introduction_wpf.aspx


You can create a dictionary of global resources and include its path in app.xaml

<Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/YourProject;Component/YourXamlFile.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>

Now all your resources in the YourXamlFile.xaml will be visible globally in your project.


Look at the section on "static resource lookup behavior" here. Anything in the application's resource dictionary (i.e. Application.Resources) is available globally. Whenever you look up a resource with a given key, and the key isn't used anywhere in the hierarchy of local resource dictionaries, the one in the application's dictionary will be returned.

To populate the application's resource dictionary in XAML, find the XAML file for the application (usually App.xaml) and add an Application.Resources element.


Just to add my 2 cents here.

I also wanted to use global resources, but I use a custom Application class, so I couldn't just put it in the App.xaml.

I created a Resources.xaml in my root location, and then did this:

Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri("/MyWpfClient;component/Resources.xaml", UriKind.Relative) });

But be warned, the Resource.xaml MUST have the Build Action to 'Page'. When it didn't it couldn't find some types I used as converters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜