Silverlight: static value binding

I need a TextBlock.Text that will be extracted from the translation manager, something like

<TextBlock Text="{Binding TranslateManager.Translate('word')}" /> 

I do not want to set a DataSource for all text blocks. The only way I found how to do this is to bind β€œstatic” to the class and use the converter:

 <TextBlock Text="{Binding Value, Source={StaticResource Translation}, Converter={StaticResource Translation}, ConverterParameter=NewProject}" /> 

And this helper class

  public class TranslationManager : IValueConverter { public static string Translate(string word) { return translate(word); } // this is dummy for fake static binding public string Value { get; set; } public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var name = parameter as string; return TranslationManager.Translate(name, name); } } 

But is there a shorter way?

+4
source share
2 answers

Let me point this out by pointing out: you should use static resources to translate words: Application resources or *. .Resx files

However, if you need to simplify your xaml, the only thing you are missing is placing a datacontext in all your eyes. It seems you are not using MVVM, so placing this logic in the constructor or your code behind gives you access to additional functions through bindings:

 public MainPage() { // Required to initialize variables InitializeComponent(); // This is the key to simplify your xaml, // you won't have set the source for individual controls // unless you want to DataContext = this; } 

Then in your xaml, your text fields can simplify this:

 <TextBlock Text="{Binding ConverterParameter=Hi, Converter={StaticResource Translator}}"/> 

My translator:

 public class Translator : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return "Hola!"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return "Hi!"; } } 
+3
source

Yes, one of the big things that Silverlight currently lacks is the support for other markup extensions - x: Staticity is one of the most painful.

What you are doing now is one way, no doubt. People have tried many ways:

http://skysigal.xact-solutions.com/Blog/tabid/427/EntryId/799/Silverlight-DataBinding-to-a-static-resource.aspx

Using Static Objects in XAML Created in Silverlight Code

But I have not found a "clean" way. At least not as clean as "{x: Static MyStaticClass.Member}"

0
source

Source: https://habr.com/ru/post/1307144/


All Articles