Imagebutton change source property

2019-09-08 04:15发布

问题:

I'm developing a Windows Phone app.

I have a custom button with an image inside. This is its XAML code:

<ControlTemplate x:Key="ImageButton" TargetType="Button">
    <Grid>
        <Image Margin="45,8,35,8" Source="Images/Delete.png"/>
    </Grid>
</ControlTemplate>

How can I change Image Source property programmatically?

回答1:

To change the source of an image you need to make a new bitmap of your asset and set it as a souce

BitmapImage myBitmapImage = new BitmapImage(new Uri("/Images/foo.png", UriKind.Relative));

imageButton.Source = myBitmapImage;

but I guess you would like to have a button that change its background if is clicked. You need to redefine Visual States of the button. Here is an example:

Windows Phone 7 (WP7) Change a button's background color on click