Change the value of the static wpf resource

How can I change the value of a static WPF resource at runtime?

I have the following resources

<UserControl.Resources> <sys:String x:Key="LengthFormat">#.# mm</sys:String> <sys:String x:Key="AreaFormat">#.# mm²</sys:String> <sys:String x:Key="InertiaFormat">#.# mm⁴</sys:String> </UserControl.Resources> 

which some text blocks reference

 <TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Path=Breadth, StringFormat={StaticResource ResourceKey=LengthFormat}}" /> 

then depending on the object associated with the control, I would like to change the formats. I set the properties in the control as follows:

 public string LengthFormat { set { this.Resources["LengthFormat"] = value; } } public string AreaFormat { set { this.Resources["AreaFormat"] = value; } } public string InertiaFormat { set { this.Resources["InertiaFormat"] = value; } } 

then before binding I set each line.

However this does not work, does someone suggest whynot?

Greetings

+6
source share
3 answers

In fact, everything works fine. But the user interface is not updated as resource keys are not observed.

You cannot use static resources if you want to change the bindings. Instead, use regular bindings using INotifyPropertyChanged for properties, allowing the user interface to observe changes.

+3
source

The most obvious way is to switch to using DynamicResource , for what it's intended.

+3
source

I agree with Klaus, since the static resource will not be respected, your user interface will not change. I would suggest trying changing a static resource to a dynamic resource

 <TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Path=Breadth, StringFormat={DynamicResource ResourceKey=LengthFormat}}" /> 
0
source

Source: https://habr.com/ru/post/905968/


All Articles