Reputation: 1988
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?
Upvotes: 0
Views: 3538
Reputation: 128061
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));
Upvotes: 0
Reputation: 63317
You can try using the FindName
method of a FrameworkTemplate
:
playSequence.Template.FindName("PlayImage", playSequence)
.SetValue(Image.SourceProperty,
new BitmapImage(new Uri(@"Pause.png", UriKind.Relative)));
Upvotes: 1