在WPF的代码区域中动态设置IMAGE的图片

两步走:

1. 使用下面代码制定文件路径

"pack://application:,,,/AssembleName;component/Resources/Port3.png"
using System.Windows.Media.Imaging;//BitmapImage

        public BitmapImage UrlToImage(string path)
        {
            BitmapImage img = new BitmapImage();
            try
            {
                img.BeginInit();
                img.UriSource = new Uri(path);
                img.EndInit();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Print("UrlToImage:"+ex.Message);
                return null;
            }

            return img;
        }

       ...
       //主程序
       //下面的AssembleName一般就是项目名称,不带任何后缀
//component是固定写法
//下面的Resources是文件夹的名字,也可以叫Images或者Files string imgPath="pack://application:,,,/AssembleName;component/Resources/Port3.png" var imgShow=new Image(){Source=UrlToImage(imgPath)};

 

2. 设置图片属性

在项目浏览器中选中图片,F4开属性,Build Action设置成Resource,默认是Content

如果这步不做,就会持续收到报错:“Cannot locate resource”

就这步我就搞了一下午。。。

 

REF:

https://stackoverflow.com/questions/350027/setting-wpf-image-source-in-code

https://stackoverflow.com/questions/11948829/wpf-throws-cannot-locate-resource-exception-when-loading-the-image

 

转载于:https://www.cnblogs.com/jiceberg420/p/9996476.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值