kirillbobyrev
kirillbobyrev

Reputation: 1739

button image changing

I'd like to change a background image of my button each time user presses it. I've set ImageSource to my picture. When mouse is over the button my button doesn't show the image. How to set the picture so that even if mouse is over button is still with image?

        <Button x:Name="recordButton" Content="" HorizontalAlignment="Left" Height="50" Margin="60,45,0,0" VerticalAlignment="Top" Width="50" Click="recordButton_Click">
        <Button.Background>
            <ImageBrush ImageSource="play.png"/>
        </Button.Background>
    </Button>

And another question. How to change those two pictures? Their names are "play.png" and "stop.png", both are located in Resources.

        private bool recordStarted = false;

    private void recordButton_Click(object sender, RoutedEventArgs e)
    {
        recordStarted = !recordStarted;


        if(recordStarted)
        {
            ImageBrush brush1 = new ImageBrush();
            BitmapImage image = Properties.Resources.stop;
            brush1.ImageSource = image;
            recordButton.Background = brush1;

        }
    }

I've tried this but VS can't find BitmapImage image = Properties.Resources.stop; Help, please !

Upvotes: 0

Views: 1512

Answers (2)

Shawn Kendrot
Shawn Kendrot

Reputation: 12465

I would recommend not setting the background to be the image, but instead set the content to be the image

<Button x:Name="recordButton" HorizontalAlignment="Left" Height="50" Margin="60,45,0,0" VerticalAlignment="Top" Width="50" Click="recordButton_Click">
    <Image Source="play.png"/>
</Button>

If you want to change the image, you can do this within text, it is easiest to use images compiled as resource rather than images in a resource file

(recordButton.Content as Image).Source = new BitmapImage(new Uri("Images/stop.png", UriKind.Relative));

If you want to use a resource file, see this SO post

Upvotes: 1

Y.Yanavichus
Y.Yanavichus

Reputation: 2417

There are some ways to change pictures:

  1. Redefine a button control template and use VisualStateManager.

  2. Redefine the control template and use Triggers.

  3. You may try to bind button's content to it's MouseOver property: when is mouse over hide one image and show another.

Upvotes: 0

Related Questions