Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for using resources in a WPF project

Tags:

resources

wpf

I know and use two methods to store and access resources on application scope:

  1. Properties\Resources.resx
  2. create a folder and place for example images there, setting their build mode to Resource

What is the difference between the two methods in terms of performance and complexity, when should each be used and how are the resources best consumed in WPF and VB or C# code in each way?

Thanks in advance,

Julian

like image 591
Julian Avatar asked May 06 '12 16:05

Julian


People also ask

What is a static resource WPF?

Static Resource - Static resources are the resources which you cannot manipulate at runtime. The static resources are evaluated only once by the element which refers them during the loading of XAML.

What are resources WPF?

A resource is an object that can be reused in different places in your application. WPF supports different types of resources. These resources are primarily two types of resources: XAML resources and resource data files. Examples of XAML resources include brushes and styles.

What is resource in XAML?

A resource is an object that can be reused in different places in your app. Examples of resources include brushes and styles. This overview describes how to use resources in Extensible Application Markup Language (XAML). You can also create and access resources by using code.


1 Answers

The "natural" way of referencing resources like images in a WPF project is your second option. You can use a relative URI to point to the image and WPF will lazy load it. You can reference resources in other assemblies using pack URI syntax.

Using Resources.resx will code-generate properties that loads resources when referenced. Resources can be strings, images, icons or a byte arrays. Using {x:Static} in XAML allows you to reference the static properties generated by the code-generator but often you will need a converter to convert the resource type into a type usable by WPF.

There is some support for localization using Resources.resx and if you want to provide a multi-lingual application you could store the translated strings in Resources.resx. However, WPF localization as described by Microsoft is not based on Resources.resx.

For images, the second option is much easier. For strings, the first option is probably easier but instead you could stay in XAML and create a ResourceDictionary.

like image 52
Martin Liversage Avatar answered Oct 05 '22 11:10

Martin Liversage