views:

156

answers:

2

I need TextBlock.Text to be retrieved from translation manager, something like

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

I don't want to set DataSource for all text blocks. The only way I found how to do this is to bind to "static" class and use converter:

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

And these 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 better - shorter - way?

A: 

Yeah, one of the big things presently lacking in Silverlight is support for other Markup extensions - x:Static being one of the more painful ones.

What you are doing now is one way, without a doubt. Folks have tried a variety of workarounds:

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

http://stackoverflow.com/questions/640154/using-static-objects-in-xaml-that-were-created-in-code-in-silverlight

But I haven't found a "clean" way yet. At least not as clean as "{x:Static MyStaticClass.Member}"

JerKimball
+1  A: 

Let me prefix this by stating: You should be using static resources for translating words: Application Resources or *.RESX Files

However, if you need to simplify your xaml, the only thing you are missing is placing a datacontext on your entire view. It sounds like you are not using MVVM, so placing this logic in the constructor or your code behind gives you access to more features through binding:

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 textboxes can simplify to 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!";
    }
}
Jeremiah