Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Localization in Silverlight 4 using ResourceWrapper

I have a business application (created from template) and I can change language dynamically by making ResourceWrapper INotifyPropertyChanged and then adding in code:

private void Language_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
 Thread.CurrentThread.CurrentCulture =
     new CultureInfo(((ComboBoxItem)((ComboBox)sender).SelectedItem).Tag.ToString());
 Thread.CurrentThread.CurrentUICulture =
     new CultureInfo(((ComboBoxItem)((ComboBox)sender).SelectedItem).Tag.ToString());
 ((ResourceWrapper)App.Current.Resources["ResourceWrapper"]).ApplicationStrings =
     new ApplicationStrings();
}

this works fine on resources referenced/binded in xaml files (i.e. MainPage frame), but it does not update references of anything I have declared in code i.e.

InfoLabel.Content = ApplicationStrings.SomeString

At the moment I'm not using ResourceWrapper. My question here is how can I change my code so it uses it and updates when ResourceWrapper change. I tried:

InfoLabel.Content = ((ResourceWrapper)App.Current.Resources["ResourceWrapper"])
    .ApplicationStrings.SomeString

but it doesn't work.

Any ideas?

like image 626
Artur Avatar asked Nov 06 '22 13:11

Artur


1 Answers

You would have to create a Binding in code. Something like this:

var b = new Binding("SomeString");
b.Source = ((ResourceWrapper)App.Current.Resources["ResourceWrapper"]).ApplicationStrings;
b.Mode = BindingMode.OneWay;
InfoLabel.SetBinding(ContentControl.ContentProperty, b);

Keep in mind that the class you bind to must implement INotifyPropertyChanged.



EDIT: If you are worried about the amount of code, just create a helper method somewhere in your app:

public Binding GetResourceBinding(string key)
        {
            var b = new Binding(key);
            b.Source = ((ResourceWrapper)App.Current.Resources["ResourceWrapper"]).ApplicationStrings;
            b.Mode = BindingMode.OneWay;

            return b;
        }

And then use the helper method like this:

InfoLabel.SetBinding(ContentControl.ContentProperty, GetResourceBinding("SomeString"));
like image 117
Henrik Söderlund Avatar answered Nov 15 '22 00:11

Henrik Söderlund