Search code examples
c#wpfdynamicresource

How to change a DynamicResource from C# code?


I have a simple "Play/Pause" button that shows the "play" icon at the start of the application. Here's its code:

<Button x:Name="playPauseButton" Style="{DynamicResource MetroCircleButtonStyle}" 
                        Content="{DynamicResource appbar_control_play}"
                        HorizontalAlignment="Left" Margin="77,70,0,0" VerticalAlignment="Top" Width="75" Height="75" Click="Button_Click"/>`

What I want to do is change the play icon to a pause icon when it's pressed. All I have to do is change the content to {DynamicResource appbar_control_pause}. However, when I do the following:

playPauseButton.Content = "{DynamicResource appbar_control_stop}";

it shows just the string literally, inside the button. How could I change that property?


Solution

  • The strings you write in XAML using { } are special (they are called Markup Extensions), so they are not treated as "strings" by the XAML processor (it instead invokes the extension to provide the resulting object, instead of assigning the string directly). In particular, you'd be using the DynamicResource markup extension here.

    But that works on the XAML processor only, so when you assign the Content property using a string from C# code, it just assigns the specific string: it's not parsed by the XAML processor at all (and the DynamicResource markup extension is never called).

    If you want to load a resource in code, you can try:

    playPauseButton.Content = FindResource("appbar_control_stop");
    

    Or, if you want to do it as DynamicResource would do it, you can try SetResourceReference, something like:

    playPauseButton.SetResourceReference(ContentControl.ContentProperty, "appbar_control_stop");
    

    This second method would assign a real reference to the resource (instead of just loading it), so if the resource changes (because the parent changes, or using events or anything), the property will be reevaluated.