How to change\set background image of a button in C# WPF code?

后端 未结 3 1939
陌清茗
陌清茗 2020-12-05 20:54

I\'m trying to change background image of my button to some other image and I encountered some errors. This is the code I have on my xaml:

    
3条回答
  •  一整个雨季
    2020-12-05 21:21

    In the build action, you can mark the image file as content or as resource. The syntax to use the image in an ImageBrush is different depending on which one you choose.

    Here is a image file marked as content.

    Image, marked as content

    To set the button background to this image use the following code.

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

    Here is an image file marked as resource.

    Image, marked as resource

    To set the button background to the resource image use the following code.

      Uri resourceUri = new Uri("Images/ResourceImage.png", UriKind.Relative);
      StreamResourceInfo streamInfo = Application.GetResourceStream(resourceUri);
    
      BitmapFrame temp = BitmapFrame.Create(streamInfo.Stream);
      var brush = new ImageBrush();
      brush.ImageSource = temp;
    
      button1.Background = brush;
    

提交回复
热议问题