I have a XAML file, where i want to replace field names with variables so i can have translation support for more languages for my application.
The way i currently use translation in my application is something like Translation.getString("stringname") (Translation is a static class with static getString function which fetches the translated string from a resource file)
Now for the xaml part I have something like this:
<TextBlock Text="Some string for translation" VerticalAlignment="Center"/>
I can do something like this:
Code:
var translatedString = Translation.getString("stringname")
Xaml:
<TextBlock Text="{Binding translatedString}" VerticalAlignment="Center"/>
But this is pretty ugly and verbose. Can i somehow access the function directly from xaml?
Such as:
<TextBlock Text="{CustomBinding stringname}" VerticalAlignment="Center"/>
Where i somewhere in my project assign that using "CustomBinding bla" will run it as a function Translation.getString("bla") and uses the returned string for my desired translation effect.
Is this possible somehow?
Is there some other "business standard" in which this is usually done?
You can do that by creating custom MarkupExtension and use that in place of Binding.
public class TranslateString : MarkupExtension
{
public string Value { get; set; }
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (String.IsNullOrWhiteSpace(Value))
return Value;
return Translation.getString(Value);
}
}
Now, you can use it from XAML like this:
<TextBlock Text="{local:TranslateString Value='Some string for translation'}"/>
Ofcourse you have to define namespace local at root level like this:
xmlns:local="clr-namespace:WpfApplication1"
Replace WpfApplication1 with actual namespace of class TranslateString.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With