8

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

Luke Woodward
  • 63,336
  • 16
  • 89
  • 104
Cadair Idris
  • 587
  • 1
  • 9
  • 20

3 Answers3

4

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

Emond
  • 50,210
  • 11
  • 84
  • 115
3

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.

Claus Jørgensen
  • 25,882
  • 9
  • 87
  • 150
0

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}}" />
Haris Hasan
  • 29,856
  • 10
  • 92
  • 122
  • 1
    I get an error saying : Error 4 A 'DynamicResourceExtension' cannot be set on the 'StringFormat' property of type 'Binding'. A 'DynamicResourceExtension' can only be set on a DependencyProperty of a DependencyObject. – Cadair Idris Jan 14 '12 at 13:52
  • ohh Right, makes sense. You won't be able to apply my solution in this case. It will only work for DependencyProperty – Haris Hasan Jan 14 '12 at 13:58