Xaml localization: Using .resx Resources in Xaml without x:static


The Microsoft recommended approach to xaml localization is using the locbaml tool. To be honest, it sucks! It has a lot of manual work and is not compatible with previous models.

Many companies have already lots of infrastructure in place for automatic support of localization. Replacing the whole infrastructure, for just a few recently added Silverlight or WPF projects does not make sense.

People give various suggestions, first thing you hear is to use x:static and .resx files. It is alright, and if it works for you then bingo. But designer does not play well with x:static, also it only works if you use the default Visual Studio resource generator to generate classes. In general I don’t like this approach.

Good news is that Dynamic objects are lovely sometimes. Xaml can use them a lot, so I create a dynamic object called ResourceLoader, and use it to load my resources from the .resx file. Then I can use binding (withe the mode=OneTime for better performance) to load resources for the right local.

<TextBlock x:Name="LoginLable" Text="{Binding Source={StaticResource ResourceKey=Res},Path=LogonText, Mode=OneTime}">
</TextBlock>

The only additional thing is to add the static resource which is the ResourceLoader somewhere in the logical tree.

<local:ResourceLoader x:Key="Res" Assembly="LogonDialog" />

The attribute “Assembly” defines the assembly which resource should be loaded from, otherwise the ResourceLoader assembly would be selected which can be wrong depending on the solution structure and location of resources.

You can download the ResourceLoader.cs from here.

Please note that you should rename the above file ResourceLoader.cs, because wordpress does not allow uploading .cs files.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: