在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

扫描二维码关注公众号,回复: 4174216 查看本文章

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

猜你喜欢

转载自www.cnblogs.com/jiceberg420/p/9996476.html