Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the value of a wpf static resource

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

like image 392
Cadair Idris Avatar asked Jan 14 '12 13:01

Cadair Idris


People also ask

How do you declare a static resource in WPF?

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.

What is StaticResource WPF?

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.

What is the difference between static resource and dynamic resource?

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.


1 Answers

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.

like image 92
Claus Jørgensen Avatar answered Sep 24 '22 06:09

Claus Jørgensen