WPF - 代码动态更换按钮的背景图片

1 相对路径

将在项目exe路径Resourc目录下寻找图片

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

2 绝对路径方式

2.1 如果图片没有导入到项目中

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

2.2 如果图片已经导入到项目中

使用@"pack://application:标志为当前项目

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;

如果有兴趣,可以访问我的个人站:http://www.stubbornhuang.com

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章