Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind a string to a dynamic resource through code in WPF

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.

like image 928
Tallang Avatar asked Oct 31 '22 22:10

Tallang


1 Answers

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")
like image 90
Dax Pandhi Avatar answered Nov 15 '22 05:11

Dax Pandhi