Ottavio Campana
Ottavio Campana

Reputation: 4188

Manipulating static resources in XAML

I am learning C#, WPF and XAML and at this point I am targeting internationalization of the product.

I can define the string that I want to translate in Resources.resx, and I would like to be able to manipulate the strings when I use them in my XAML files. Let's make an example, supposing to have a label like this

<Label Grid.Column="0" Grid.Row="0" Content="{x:Static p:Resources.username}" />

In Resources.resx I define name username with value username and the label gets the correct value.

Suppose now that I want to display another label, but this time I want to display the text Username, with capital u. The immediate solution would be defining name Username value Username, but I am getting a duplicated resource. In other templating systems, such as in django, I can use the initial resource and and I can apply a filter to modify the string, but I am not able to achieve this in C#.

Is there a way to manypulate static resources in C# and XAML, for example to apply a converter that capitalizes the first letter of the string?

Upvotes: 3

Views: 709

Answers (1)

Rekshino
Rekshino

Reputation: 7325

Binding has a Converter property. So you can do bind to the static resource and use a converter to modify the value:

<Window.Resources>
    <local:StrToLowerValueConverter x:Key="strToLowerCnv"/>
</Window.Resources>
<Label Grid.Column="0" Grid.Row="0" Content="{Binding Source={x:Static p:Resources.username}, Mode=OneWay, Converter={StaticResource strToLowerCnv}}" />

And the converter itself:

public class StrToLowerValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (value as string)?.ToLower() ?? value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Upvotes: 2

Related Questions