Search code examples
c#wpfbuttoncontroltemplates

Change button image source WPF


I have a button with a template.

I would like to dynamically change the image source from the code behind.

Here is my code:

<Button Height="48" HorizontalAlignment="Left" Name="playSequence" VerticalAlignment="Top" Width="49" Click="PlaySequenceButton_Click" Grid.Column="1" Margin="10,0,0,0">
    <Button.Template>
        <ControlTemplate>
            <Border HorizontalAlignment="Center" VerticalAlignment="Center" >
                <Image Name="PlayImage" Source="Play.png" Width="45" Height="41" Stretch="Fill"/>
            </Border>
        </ControlTemplate>
   </Button.Template>
</Button>

When I type this code:

PlayImage.Source = new BitmapImage(new Uri(@"Pause.png", UriKind.Relative));

PlayImage is not recognized.

Is there any way to change the button's image source that way?


Solution

  • You might prefer to set the image by means of the Button's Content property in a Style like this:

    <Button ...>
        <Button.Style>
            <Style TargetType="Button">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="Button">
                            <Border ...>
                                <Image Source="{TemplateBinding Content}"
                                       Width="45" Height="41" Stretch="Fill"/>
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
                <Setter Property="Content">
                    <Setter.Value>
                        <BitmapImage UriSource="Play.png"/>
                    </Setter.Value>
                </Setter>
            </Style>
        </Button.Style>
    </Button>
    

    Now you could simply change the image by setting the Content property:

    playSequence.Content = new BitmapImage(new Uri(@"Pause.png", UriKind.Relative));