How to reference a recourse file from a class in WPF

  • Thread starter Thread starter moondaddy
  • Start date Start date
M

moondaddy

I have a WPF windows app and from code in Window.xaml.cs I create an
instance of a class whish is derived from Adorner. In this class I create
shapes and need to apply a style from a resource file named
'Dictionary1.xaml'.

Normally if all this code was just running in Window.xaml.cs I could use
this line:

cornerThumb.Style = (Style)this.FindResource("RoundThumbLineEnd");

and use this reference in the window's xaml:

<Window.Resources>
<ResourceDictionary Source="Dictionary1.xaml" />
</Window.Resources>

but of course, the Adorner class where I'm working has no idea where
Dictionary1.xaml is.

Any tips?

Thanks.
 
Hi moondaddy,

When finding a resource, it first checks the current element's Resources
collection (its resource dictionary). If the item is not found, it checks
the parent element, its parent, and so on until it reaches the root
element. At that point, it checks the Resources collection on the
Application object. If it is not found there, it finally checks a system
collection (which contains system-defined fonts, colors, and other
settings). If the item is in none of these collections, it throws an
InvalidOperationException.

Therefore you could simply put resources in App.xaml within
<Application.Resources> and those resources will be shared by all your code
in the same assembly.

For ResourceDictionary defined in separate .xaml files, you could use
following code to load it:

ResourceDictionary rd = new ResourceDictionary();
rd.Source = new Uri(@"Dictionary1.xaml", UriKind.Relative);

Then you can use rd["resource_key"] to reference each resource.

Hope this helps.


Regards,
Walter Wang ([email protected], remove 'online.')
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.
 
Back
Top