Cadair Idris
Cadair Idris

Reputation: 607

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

Upvotes: 8

Views: 13547

Answers (3)

Emond
Emond

Reputation: 50672

The most obvious way is to switch to using DynamicResource that is what it is for.

Upvotes: 4

Haris Hasan
Haris Hasan

Reputation: 30097

I agree with Claus as the static resource won't be observed your UI won't change. I would suggest try by changing static resource into dynamic resource

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

Upvotes: 0

Claus J&#248;rgensen
Claus J&#248;rgensen

Reputation: 26347

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.

Upvotes: 3

Related Questions