Static extension in WPF XAML and public ResX files

For the localization or some other reason you might want to access the static resources in ResX file from the XAML using Static extension. For example:

<TextBlock Text="{x:Static r:Resource.UserNameCaption}" />

By default, when we create a new ResX file and add some resources, Visual Studio marks them with the internal access modifier. If we look at Resource.Designer.cs we will see the following code for UserNameCaption string resource:

internal static string UserNameCaption {
    get {
        return ResourceManager.GetString("UserNameCaption"resourceCulture);
    }
}

The  problem is that if we try to run application we get the XAMLParseException with the message:

StaticExtension value cannot be resolved to an enumeration, static field,
or static property.

It’s caused by the internal modifier and the solution is to change it to public. However, we can’t do that directly because Visual Studio overwrites Design.cs file after any changes in ResX one. So, first, let’s take a look at the properties of ResX file:

Static extension in WPF XAML and public ResX filesVisual Studio uses ResXFileCodeGenerator as a Custom Tool by default. Unfortunately, there is no hint that we can set another generator called PublicResXFileCodeGenerator:

Static extension in WPF XAML and public ResX files 2

After changing Custom Tool Visual Studio automatically updates Resource.Designer.cs file and sets public modifier for all resources:

public static string UserNameCaption {
    get {
        return ResourceManager.GetString("UserNameCaption"resourceCulture);
    }
}

From now we can use Static extension in XAML without errors.

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