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?
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"));
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