0

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>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Zoey
  • 25
  • 8
  • 1
    i would refer to this similar question as to how this isn't a good idea, http://stackoverflow.com/questions/8313360/altering-a-controltemplate-from-code-behind – Kevin Nacios Jan 03 '14 at 02:33

3 Answers3

1

Try this to get Image control from code :

var template = mediaControlButton.Template;
var imageControl = (Image)template.FindName("iconPlaying", mediaControlButton);
har07
  • 88,338
  • 12
  • 84
  • 137
0

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

Kevin Nacios
  • 2,843
  • 19
  • 31
0

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

Community
  • 1
  • 1
NattyMan0007
  • 103
  • 13