ImageSourceConverter 抛出 NullReferenceException ......为什么? [英] ImageSourceConverter throws a NullReferenceException ... why?

查看:48
本文介绍了ImageSourceConverter 抛出 NullReferenceException ......为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去一个小时左右,我一直在为这个问题纠结.

I've been tearing my hair out over this issue for the last hour or so.

我有一些代码是这样的:

I have some code that goes like this:

videoTile.Icon = new ImageSourceConverter().ConvertFrom(coDrivr4.Properties.Resources.Music.GetHbitmap()) as ImageSource;

当我运行我的代码时,它说发生了 NullReferenceException.'Music' 和 GetHbitmap() 的返回都不为空.

When I run my code, it says a NullReferenceException occurred. Neither 'Music' nor the return of GetHbitmap() are null.

我正在尝试通过属性获取图像,因为这是我想出如何访问我的资源文件夹中的图像的唯一方法.我只是将它们作为资源添加到 app.xaml 文件中,但由于某些原因我没有使用 app.xaml 文件.

I'm trying to get the image via the Properties because it's the only way I've figured out how to access the images in my Resources folder. I would just add them to the app.xaml file as a resource, but I'm not using an app.xaml file for a few reasons.

我这样做错了吗?我需要做的就是获取我的 Resource 目录中的图像的 ImageSource 对象.我可以在我的 XAML 中很好地使用它们,但我一生都不能在任何代码中使用它们.

Am I attempting this wrong? All I need to do is get an ImageSource object of an image I have in my Resource directory. I can use them just fine in my XAML, but can't for the life of me do it in any code.

P.S.:我不能将它们作为资源添加到 XAML 文件中,因为这只是一个类,因此没有 XAML 文件.

P.S.: I can't just add them as a resource to the XAML file because this is just a class and so there is no XAML file.

推荐答案

好吧,您有很多可能为空的东西.我建议你把它们分开:

Well you've got plenty of things which could be null in there. I suggest you separate them out:

Bitmap bitmap = coDrivr4.Properties.Resources.Music;
object source = new ImageSourceConverter().ConvertFrom(bitmap.GetHbitmap());
ImageSource imageSource = (ImageSource) source;
videoTile.Icon = imageSource;

注意这里使用的是强制转换而不是 as 运算符.如果 source 不是 ImageSource,这将抛出一个 InvalidCastException 这将比仅仅结束更具描述性作为一个空引用.

Note the use of a cast rather than the as operator here. If source isn't an ImageSource, this will throw an InvalidCastException which will be much more descriptive than just ending up as a null reference.

好的,现在我们确定它发生在 ConvertFrom 中,我建议下一步是找出它是否是 .NET 4.0 beta 1 中的错误.你真的在使用吗?任何 .NET 4.0 功能?我建议您尝试将那部分代码提取到一个单独的项目中(您不需要显示 API,只需转换图像.尝试在 .NET 3.5 中运行该代码.如果它以同样的方式失败,这从可能的问题列表中消除了 beta 性.

Okay, so now we know for sure that it's happening in ConvertFrom, I suggest the next step is to find out whether it's a bug in .NET 4.0 beta 1. Are you actually using any .NET 4.0 features? I suggest you try to extract just that bit of code into a separate project (you don't need to display an API, just convert the image. Try to run that code in .NET 3.5. If it fails in the same way, that's eliminated the beta-ness from the list of possible problems.

这篇关于ImageSourceConverter 抛出 NullReferenceException ......为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆