WPF - Code to dynamically change the background image of a button

WPF - code to dynamically replace the background picture of the button
Article directory
1 Relative path
2 Absolute path method
2.1 If the picture has not been imported into the project
2.2 If the picture has been imported into the project
1 Relative path
will look for the picture in the project exe path Resourc directory

ImageBrush brush1 = new ImageBrush();
string path = @"Resource/icon-submit.png";
BitmapImage img = new BitmapImage(new Uri(path, UriKind.Relative));
brush1.ImageSource = img;
Testbutton.Background = brush1 ;

2 Absolute path method
2.1 If the image is not imported into the project
ImageBrush brush1 = new ImageBrush();
string path = @"F:/Resource/icon-submit.png";
BitmapImage img = new BitmapImage(new Uri(path, UriKind .Absolute));
brush1.ImageSource = img;
Testbutton.Background = brush1;

2.2 If the image has been imported into the project,
use the @"pack://application: flag as the current project

ImageBrush brush1 = new ImageBrush();
string path = @"pack://application:,,,/Resource/icon-提交.png";
BitmapImage img = new BitmapImage(new Uri(path, UriKind.Absolute));
brush1.ImageSource = img;
Testbutton.Background = brush1;
 

Guess you like

Origin blog.csdn.net/u014090257/article/details/130961919