Ima??geSourceConverter抛出NullReferenceException...为什么?在过去一个小时左右的时间里,我一直在为这个问题焦头烂额。我有一些这样的代码:videoTile.Icon=newImageSourceConverter().ConvertFrom(coDrivr4.Properties.Resources.Music.GetHbitmap())asImageSource;当我运行我的代码时,它说发生了NullReferenceException。“Music”和GetHbitmap()的返回值都不为空。我试图通过属性获取图像,因为这是我弄清楚如何访问资源文件夹中图像的唯一方法。我只是将它们作为资源添加到app.xaml文件中,但出于某种原因我没有使用app.xaml文件。我在尝试做错什么吗?我需要做的就是为我的资源目录中的图像获取一个ImageSource对象。我可以在我的XAML中使用它们,但不能在我生活中的任何代码中使用。PS:我不能只将它们作为资源添加到XAML文件中,因为这只是一个类,没有XAML文件。然后你有很多东西可以在那里失效。我建议你把它们分开:Bitmapbitmap=coDrivr4.Properties.Resources.Music;objectsource=newImageSourceConverter().ConvertFrom(bitmap.GetHbitmap());ImageSourceimageSource=(ImageSource)来源;videoTile.Icon=imageSource;注意这里使用cast而不是as运算符。如果source不是ImageSource,将抛出InvalidCastException,这比最终作为null引用更具描述性。编辑:好的,既然我们已经确定ConvertFrom会发生这种情况,我建议下一步是查明它是否是.NET4.0beta1中的错误。您实际上是否在使用任何.NET4.0功能?我建议您尝试将此代码提取到一个单独的项目中(您不需要显示API,只需转换图像。尝试在.NET3.5中运行该代码。如果它以同样的方式失败,则可能来自Eliminatedbeta-ness从问题列表中。我遇到了完全相同的问题-我将所有位图都放在一个漂亮的静态类型资源文件中,我只是想用它们设置一个ImageSource。因此,由于ImageSourceConverter抛出了Gettinganullreferenceexception,我改变了方向并使用了这段代码:Bitmapbitmap=entityCol.EntityCollectionImage;this.Image=System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(),IntPtr.Zero,Int32Rect.Empty,BitmapSizeOptions.FromEmptyOptions());//Image是一个图像源希望能有所帮助。这不是.netFramework中的错误,这个空引用异常的发生是因为ImageSourceConverter无法转换Bitmap类型对象,它可以转换为:Stream、string、Uri、byte[],因此您必须将代码更改为如下内容:varimageSourceConverter=newImageSourceConverter();byte[]tempBitmap=BitmapToByte(eventArgs.Frame);ImageSource图像=(ImageSource)imageSourceConverter.(MemoryStreamstream=newMemoryStream()){bitmap.Save(stream,System.Drawing.Imaging.ImageFormat.Bmp);stream.Close();byteArray=stream.ToArray();}返回字节数组;在使用ConvertFrom之前将您的位图保存到MemoryStream位图canvas=newBitmap(secScreen.Bounds.Width,secScreen.Bounds.Height);图形g=Graphics.FromImage(canvas);g.Clear(System.Drawing.Color.Yellow);MemoryStreamstream=newMemoryStream();canvas.Save(stream,System.Drawing.Imaging.ImageFormat.Png);ImageSourceisrg=(ImageSource)newImageSourceConverter().ConvertFrom(stream);试试coDriver4.将Properties.Resources.Music.GetHbitmap()的返回值放入temp变量中,看是否为null——也许null就是从这里来的上面是C#学习教程:ImageSourceConverterthrowsNullReferenceException...why?如果所有分享的内容对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
