Static extension in WPF XAML and public ResX files
For 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 the 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:
Visual Studio uses ResXFileCodeGenerator
as a Custom Tool
by default. Unfortunately, there is no hint that we can set another generator called PublicResXFileCodeGenerator
:
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.