How to change the background image of button on runtime?

前端 未结 3 1415
逝去的感伤
逝去的感伤 2021-01-19 21:12

I m stuck with a problem. I want to change the background image of button on runtime. I got the solution for changing the color but i want to change the image.

The c

3条回答
  •  时光说笑
    2021-01-19 22:03

    Something like this?

    var brush = new ImageBrush();
    brush.ImageSource = new BitmapImage(new Uri(@"Images/myImage.png", UriKind.Relative)); 
    myButton.Background = brush;
    

    [Edit] I made a test application with two images. I toggle the image on button click and it works.

    private bool flag;
    
    private void button1_Click(object sender, RoutedEventArgs e)
    {
        flag = !flag;
    
        var uriString = flag ? @"Images/logo.png" : @"Images/icon.png";
        myButton.Background = new ImageBrush 
            { ImageSource = new BitmapImage(new Uri(uriString, UriKind.Relative)) };
    }
    

提交回复
热议问题