0

I have a button:

<Button Name="btnPlayPause" HorizontalAlignment="Left" VerticalAlignment="Top" Height="30" Margin="8,10,0,0" Cursor="Hand" Click="btnPlayPause_Click">
    <Button.Template>
        <ControlTemplate>
            <Image Name="btnPlayPause_Image" Source="Images/Pause.png"/>
        </ControlTemplate>
    </Button.Template>
</Button>

I want to change the Image (in the ControlTemplate) in C#. I am doing it like:

//changing icon
BitmapImage iconPlay = new BitmapImage();
iconPlay.BeginInit();
iconPlay.UriSource = new Uri("images\\Play.png", UriKind.Relative);
iconPlay.EndInit();

btnPlayPause_Image.Source = iconPlay;

But I can't access btnPlayPause_Image. It Says It doesn't exists in the current context.

But why??

When I create button without ControlTemplate:

<Button Name="btnPlayPause" HorizontalAlignment="Left" VerticalAlignment="Top" Height="30" Margin="8,10,0,0" Cursor="Hand" Click="btnPlayPause_Click">
    <Image Name="btnPlayPause_Image" Source="Images/Pause.png"/>
</Button>

C# Code works fine. It finds the btnPlayPause_Image and changes the image source successfully:

1 Answer 1

1

The Image is not in the scope of the window. It's in the scope of the Template of the Button. So you have to use the method FindName of the Button's Template like this:

var img = btnPlayPause.Template.FindName("btnPlayPause_Image", btnPlayPause) as Image;   //second parameter is the "ParentTemplate"
if(img != null) img.Source = iconPlay;
1
  • 1
    It takes one more argument. ParentTemplate. I fixed it.
    – Shaharyar
    Oct 16, 2014 at 7:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.