How to bind a string to a dynamic resource through code in WPF
Asked Answered
B

1

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.

Blanchard answered 7/8, 2015 at 7:16 Comment(2)
Does your SampleViewModel class implement INotifyPropertyChanged? Do you set again SampleText property (in your code) after you change the application culture?Mccarty
Yes SampleViewModel implements Conductor<object>.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.Blanchard
P
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")
Peptone answered 9/10, 2015 at 4:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.