How can i change the value of a WPF static 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 textblocks reference
<TextBlock Grid.Row="2" Grid.Column="1"
Text="{Binding Path=Breadth, StringFormat={StaticResource ResourceKey=LengthFormat}}" />
then depending on the object to be bound to the control i would like to change the formats. I have set up 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 string.
However it doesn't work, anyone suggest whynot?
Cheers
Static Resource - Static resources are the resources which you cannot manipulate at runtime. The static resources are evaluated only once by the element which refers them during the loading of XAML.
StaticResources are resolved at compile time. Using StaticResource In WPF.zip. Updated 8/29/2018 - Formatted. Resources provide a simple way to reuse commonly defined objects and values. If we are defining the resource then we can use that resource a number of times.
StaticResource are retrieved only once by the referencing element and used for entire life of the resource. On the other hand, DynamicResource are acquired every time the referenced object is used.
Actually it works just fine. But the UI isn't updated, as the resource keys aren't being observed.
You shouldn't use static resources, if you want bindings that can change. Use regular bindings instead, with INotifyPropertyChanged
on the properties, allowing the UI to observe changes.
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