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

本文介绍了在WPF应用中如何通过代码来动态更换按钮的背景图片,包括使用相对路径和绝对路径两种方式。对于相对路径,图片需放在项目exe路径下的Resources目录;而对于绝对路径,可以直接指定图片在硬盘上的完整路径。如果图片已导入项目,可以使用pack协议来引用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

WPF - 代码动态更换按钮的背景图片
文章目录
1 相对路径
2 绝对路径方式
2.1 如果图片没有导入到项目中
2.2 如果图片已经导入到项目中
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;
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值