Zoey
Zoey

Reputation: 25

wpf can't change the source of a image in Code Behind

I am currently working a new project and I need to change the source of a image in my WPF project, but when I'm going into the Code Behind, it can't find the name in the context. Here my code :

    <Button x:Name="mediaControlButton" Width="20" Height="20" Margin="161,54,219,26">
        <Button.Template>
            <ControlTemplate>
                <Border HorizontalAlignment="Center" VerticalAlignment="Center" >
                    // This is the image I need to change the source wich the Code Behing can't find.
                    <Image x:Name="iconPlaying" Source="Resources/play.png" 
                           Width="20" 
                           Height="20"/>
                </Border>
            </ControlTemplate>
        </Button.Template>
    </Button>

Upvotes: 0

Views: 1021

Answers (3)

NattyMan0007
NattyMan0007

Reputation: 103

try:

var iconplaying = (mediaControlButton.Content as System.Windows.Controls.Image);    
iconplaying.Source = "theimage.png"

and bind it to the image in the xaml

also have a look at this post

WPF Image Dynamically changing Image source during runtime

Upvotes: 0

Kevin Nacios
Kevin Nacios

Reputation: 2853

here is an alternative to attempting to modify the template in the code behind. with this, you wont be modifying the template but the content of the button (which should really be independent of the control template anyway)

<Button x:Name="mediaControlButton" Width="20" Height="20" >
    <Button.Template>
        <ControlTemplate TargetType="Button">
            <Border HorizontalAlignment="Center" VerticalAlignment="Center" BorderBrush="Red" BorderThickness="2" >
                <ContentControl Content="{TemplateBinding Content}"/>
            </Border>
        </ControlTemplate>
    </Button.Template>

    <Image x:Name="buttonImage" Source="Resources/left.jpg"
           Width="20" 
           Height="20"/>
</Button>

this way, whatever you throw in the Button.Content property will be set in the ContentControl of the ControlTemplate

In the code behind you can get the image like this:

var iconplaying = (mediaControlButton.Content as System.Windows.Controls.Image);
iconplaying.Source = "whatever.png";

If the control template for this button is going to be used in more than one place, you should define it as a Style

Upvotes: 0

har07
har07

Reputation: 89325

Try this to get Image control from code :

var template = mediaControlButton.Template;
var imageControl = (Image)template.FindName("iconPlaying", mediaControlButton);

Upvotes: 1

Related Questions