Home > Software engineering >  How to use Converters without binding value
How to use Converters without binding value

Time:09-19

maybe my question is stupid, but is it possible to use converters for string literals without binding to value? In my case converter is used for translation (literal (key in resx) is text in default language and converted value is translated text).

  1. I can create string property inside my ViewModel, but there are a lot of such literals, and it can make a mess in view model.
  2. Another solution is to bind value directly to resx:
<TextBlock Text="{x:Static SomeResxFile.Employees, Converter=...}" />

But there can be spaces in my resx key, so this approach does not work.

I do not want to create property for every label in my app, but I also want to use strings with spaces as key in my resx.

What I want to reach:

<TextBlock Text="{Binding Value="Add employee", Converter=...}" />

CodePudding user response:

you can use Binding extension (to get advantage of converter) by explicitly setting binding Source (without using DataContext):

<TextBlock Text="{Binding Source='Add employee', Converter={StaticResource SomeConverter}}" />

or reference project resources:

<TextBlock Text="{Binding Source={x:Static SomeResxFile.Employees}, Converter={StaticResource SomeConverter}}" />

CodePudding user response:

"{x:Static SomeResxFile.Employees, Converter=..}" is not valid.

You can use markup extension instead, take a look (pseudo xaml)

<UserControl xmlns:loc="clr-namespace:[Namespace where LocalizationExtension is defined];assembly=[assembly name where LocalizationExtension is defined]">
    ..
    <TextBlock Text="{loc:Localization SomeResxFile.Employees}"/>
    ..
</UserControl>

Where LocalizationExtension is

public class LocalizationExtension : MarkupExtension
{
    public string Str { get; set; }

    public LocalizationExtension(string str)
    {
        Str = str;
    }

    public LocalizationExtension()
    {
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        var newString = "translated string";
        return newString;
    }
}

This way, the Text of TextBlock will be the returned text from ProvideValue function.

  • Related