在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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM