tags:

views:

234

answers:

3

I have a ControlTemplate which is for the Button control, in the ControlTemplate I have Image control which is used to displayed in the button, Now I want to set the Image Source at runt time as I have to copy paste the ControlTemplate for each of the button to set new image for new button.

Thanks in advance.

+1  A: 

Generally speaking there are two ways you can set an image source at run time (the code samples below are in pseudo-code and would not compile):

1) In XAML using binding where the source of the binding will be some object's property containing the image source (this is the scenario Slugster was talking about):

This would be your object:

public class ViewModel
{
  public string ImageURI {get;set;}
}

and will be presented by XAML where you have your button with image, and image source is set through binding:

<Image Source="{Binding Source=ViewModel; Path=ImageURI}"/>

2) By setting the image source from code-behind.

this will be your XAML where you have the button with image:

<Image x:Name="theImage"/>

and in the code-behind you set the source of that image:

theImage.Source = new BitmapImage(new Uri("yor image uri"));
Alex_P
In my case The image control in placed in the ControlTemplate and I have to assign the Source of the Image control , right now I am assigning it in ControlTemplate and I have created ControlTemplate for every button on which I have to apply the style. My Question is that I want to create One controlTemplate for all button control and in that ControlTemplate I want to assign, not in the controlTemplate.hope you get my point
Asim Sajjad
A: 

You can access an item from inside the template by using the GetTemplateChild(string childName) method (with the name of your element as defined in the XAML), for example - If your image was defined like this:

<Image x:Name="MyImage" Stretch="Fill" />

then you would call this method like this:

Image myImage = GetTemplateChild("MyImage") as Image;

if (myImage != null)
{
    myImage.Source = "/Images/MyPicture.jpg";
}

Note: You will not be able to use this method until AFTER OnApplyTemplate has been called for the control.

Gabriel McAdams