我目前正在开发一个卡DLL,我需要将每张卡的图像文件作为嵌入式资源,当前项目如下所示:
注意:卡片图像(.png)位于Resources文件夹中.
Assembly _assembly; Stream _imageStream; private Image img; public Image Img { get { return img; } } public Kaart() : this(5,"Spades") { } public Kaart(int val,string s) { this.KaartWaarde = val; this.Figuur = s; this._imageStream = imgS(); this.img = new Image(_imageStream); } private Stream imgS() { try { _assembly = Assembly.GetExecutingAssembly(); Stream s = _assembly.GetManifestResourceStream(string.Format("{0}{1}.png",this.kaartWaarde,this.figuur.Substring(0,1))); if (s != null) return s; else return null ; } catch { throw new Exception("Kaart kan niet geladen worden."); } }
我似乎得到的唯一例外是在创建Kaart对象时的异常,代码在这里:
Kaart k = null; try { k = new Kaart(); } catch (Exception ex) { MessageBox.Show(ex.Message); //This MessageBox is being shown } ImageSourceConverter c = new ImageSourceConverter(); testBox.Source = (ImageSource)c.ConvertFrom(k.Img);
Value of ‘null’ is not valid for ‘stream’.
在代码执行期间观察我的变量时,我注意到了某种方式
Stream s = _assembly.GetManifestResourceStream(string.Format(“{0} {1} .png”,1)));
即使使用Kaarten格式,也无法找到图像.{0} {1} .png
这简直让我想知道我在这里做错了什么,或者我是否使用了错误的语法.有任何想法吗?
编辑:
现在正在正确加载图像,但ImageSourceConverter仍然抛出NullReferenceException
卡创作&加载Stream对象(并将它们卸载到Image对象中)现在可以正常工作,但是当我尝试使用下面的代码在我的WPF Image控件中实际显示图像时,会抛出NullRefException.
Kaartspel kaarten = new Kaartspel(); Kaart k = kaarten.kaarten[7]; ImageSourceConverter c = new ImageSourceConverter(); testBox.Source = (ImageSource)c.ConvertFrom(k.Img); //Exception here