6

I am currently working on a project where I use Caliburn to bind between View and ViewModel. In order to be able to switch between languages during runtime, I have separate resource files containing all the strings used in the application. Some of the e.g. TextBlock Text-bindings are bound to one of the string resources like so:

SampleView.xaml <TextBlock Text={DynamicResource Foo.Bar.Baz} .../>

Language.en-US.xaml <system:String x:Key="Foo.Bar.Baz">Im a string</system:String>

When I change the culture of my application to a different language, the dynamic binding to Foo.Bar.Baz makes the string update to the new language during runtime. Great!

However, some of the Text-properties in the application is bound to a string in the ViewModel with Caliburn like so:

SampleView.xaml <TextBlock Text={Binding SampleText} .../>

SampleViewModel.cs public string SampleText { get; set; }

The value of SampleText is set to a string resource from Language.en-US.xaml like so: ... SampleText = Application.Current.FindResource("Foo.Bar.Baz") as string; ...

Unfortunately, when I change the application culture, the string SampleText is not updated.

The question is therefore: How can I set SampleText to a string resource from Language.en-US.xaml which will automatically update itself when I change the application culture?

NOTE: Through the comments on this StackOverflow question I read that it was possible through a bindnig like so: SampleText = Application.Current.Resource["Foo.Bar.Baz"] as string; However, this did not work for me.

Community
  • 1
  • 1
Tallang
  • 143
  • 2
  • 7
  • 1
    Does your SampleViewModel class implement INotifyPropertyChanged? Do you set again SampleText property (in your code) after you change the application culture? – Il Vic Aug 07 '15 at 07:19
  • Yes `SampleViewModel` implements `Conductor.Collection.OneActive` from Caliburn, so one way to update `SampleText` after changing application culture is to set `SampleText = Application.Current.FindResource("Foo.Bar.Baz");` every time I change culture. However I find this to be a bad sollution, considering my application has TextBlock bindings like that all over the place. – Tallang Aug 07 '15 at 07:31

1 Answers1

3

You can reference your resource as a DynamicResource. To do this in code behind:

frameworkElement.SetResourceReference(dependencyProperty, resourceKey);

For example:

mySampleTextBlock.SetResourceReference(TextProperty, "Foo.Bar.Baz")
Dax Pandhi
  • 843
  • 4
  • 13