WPF UserControl 加载时抛出 NullReferenceException [英] WPF UserControl throws NullReferenceException when loading

查看:28
本文介绍了WPF UserControl 加载时抛出 NullReferenceException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有主 WindowUserControl 的 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屋!

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