Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Databind Resource File in XAML

For localization I'm using the Resource-file (.resx files) functionality in .NET, but I'm wondering if there's a smart way to databind the various localization properties directly in XAML?

The resource file only seems to expose static properties, which I can't figure out how to bind from a viewmodel, or other resource dictionary.

Also, if it's possible, I'd like it to work at design-time with Expression Blend.

like image 212
Douglas Grube Avatar asked Sep 20 '11 19:09

Douglas Grube


People also ask

How do you bind property in XAML?

One-Way Data Binding The following XAML code creates four text blocks with some properties. Text properties of two text blocks are set to “Name” and “Title” statically, while the other two text blocks Text properties are bound to “Name” and “Title” which are class variables of Employee class which is shown below.

What does RESX file contains?

resx file contains a standard header, which describes the format of the resource entries and specifies the versioning information for the XML that is used to parse the data. The resource file data follows the XML header.


1 Answers

Here is how I do it.

WPF:

  1. Create a resource file and in the same assembly create a class that has a public constructor. Make sure the resource file is marked public.

  2. In your xaml file - add a reference to this location in the namespaces

    xmlns:res="clr-namespace:MyProject.StringResources"

  3. For your text property use the following binding

    TextProperty="{x:Static res:ResourceFileName.ResourceKey}"

Silverlight:

  1. Follow steps 1 & 2 above and then add the resource file as a Resource in either your user control or in an application level resource:

    <res:ResourceFileName x:Key="resourcesLabels"/>

  2. For your text property use the following binding:

    TextProperty="{Binding ResourceKey, Source={StaticResource resourceLabels}}"

like image 146
tsells Avatar answered Sep 28 '22 02:09

tsells