Changing resource in the runtime

1.4k views Asked by At

Let's suppose, that we've got the following dictionary:

<ResourceDictionary xmlns:sys="clr-namespace:System;assembly=mscorlib">
    <sys:String x:Key="Test">Ala ma kota</sys:String>
</ResourceDictionary>

This dictionary is merged somewhere in custom control:

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="MyDictionary.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>

How can I completely change value of the resource "Test" during application runtime from the code behind?

2

There are 2 answers

0
dev hedgehog On

If you are looking to change a resource from code behind then just access the resource like a dictionary and change desired value :)

Like this:

this.Resource["myThickness"] = new Thickness(2);

That would be it :)

0
Rohit Vats On

You can change resource from code-behind but main thing is how you are binding to that resource i.e. via StaticResource or DynamicResource.

Modify like this -

Resources["Test"] = "Ala ma kota updated";

XAML (After resource update from code behind, text value will differ for two approaches) -

<TextBlock Text="{StaticResource Test}"/>  // Will be Ala ma kota
<TextBlock Text="{DynamicResource Test}"/> // Will be Ala ma kota updated