WPF UserControl 加载时抛出 NullReferenceException [英] WPF UserControl throws NullReferenceException when loading
问题描述
我有一个带有主 Window
和 UserControl
的 WPF 项目.
I have a WPF project with a main Window
and a UserControl
.
在 Usercontrol
中,我使用 gridcontrol.ItemsSource = query.tolist()
设置了一个 GridControl.ItemsSource
,但是在加载 Usercontrol
它抛出一个 Exception
:
In the Usercontrol
I set a GridControl.ItemsSource
using gridcontrol.ItemsSource = query.tolist()
, but when loading the Usercontrol
it throws an Exception
:
未将对象引用设置为对象"
"The object reference not set to an object"
尽管查询返回了 40 行数据.
In spite of the query returning 40 rows of data.
代码在 MainWindow 中执行,但 UserControl
抛出异常.
The code is executed in the MainWindow but the UserControl
throws the exception.
推荐答案
从对问题的评论中整合对话:
Consolidating the conversation from the comments on the question:
一个 NullReferenceException
被抛出在线
gridcontrol.ItemsSource = query.ToList();
因为 gridcontrol
为空.
有关此Exception
的更多信息,请参阅什么是 NullReferenceException,我该如何解决?
For more information on this Exception
see What is a NullReferenceException, and how do I fix it?
我猜有问题的行是在构造函数中调用 InitializeComponent()
之前.
I'm guessing that the line in question is before the call to InitializeComponent()
in the constructor.
此方法初始化UserControl
中的所有控件.因此,如果在调用此方法之前尝试使用 Control
,它将抛出 NullReferenceException
.
This method initialises all of the controls in the UserControl
. Therefore, if trying to use a Control
before a call to this method, it will throw a NullReferenceException
.
您希望看到的是:
public YourUserControl()
{
InitializeComponent();
gridcontrol.ItemsSource = query.ToList();
}
这篇关于WPF UserControl 加载时抛出 NullReferenceException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!