10

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.

Douglas Grube
  • 128
  • 1
  • 9

2 Answers2

20

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}}"

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
tsells
  • 2,751
  • 1
  • 18
  • 20
  • 1
    That seems to work for WPF. However, for Silverlight `x:Static` doesn't seem to be supported. Any ideas on how to handle that? – Douglas Grube Sep 20 '11 at 19:50
2

Very similar to what Geek proposed, but even a bit easier I think:

Create a class in the same assembly, which inherits the resources file and exposes a public constructor, then use this class instead.

public class ResourcesProxy : Properties.Resources
{
    /// <summary>
    /// resolves the problem of internal constructor in resources.designer.cs
    /// in conjunction with xaml usage
    /// </summary>
    public ResourcesProxy() : base()
    {
    }
}
Mike Fuchs
  • 12,081
  • 6
  • 58
  • 71