设置 WPF 的 Textblock.Text 属性将引发 NullReferenceException


textBlock.Text = "Text";

这是我的代码,它没有显示错误。但是当我运行它时,我得到一个NullReferenceException

Object reference not set to an instance of an object.

这个语句是在Slider的ValueChanged事件中,如果有关系的话

我假设这段代码在构造函数中。确保在执行这一行之前调用了InitializeComponents:

public YourWindow()
{
    TextBlock.Text = "Text"; // <- bad
    InitializeComponents();
    TextBlock.Text = "Text"; // <- good
}

如果这是在编译时,甚至不是在运行时,似乎你对Textblock对象的引用是不对的。

这就是你的代码吗?在XAML中尝试以下操作:

<TextBlock x:Name="myTextBlock" />

在你的CS文件中:

myTextBlock.Text = "Text";

"valuechanged"事件已经在InitializeComponent()调用中发生。所以你可能需要在你的算法中做的是检查文本框== null(如果这是真的,不要做任何事情!…)。

有同样的问题,但已经有这个线程打开,所以…虽然晚了,但希望它能很快帮助到其他人。

如果你的TextBlock定义不是这个<TextBlock x:Name="TextBlock"/>,那么你的程序根本不编译。

但是如果是这样的话,那么就确保在访问任何子窗口之前执行窗口构造函数中的InitializeComponent()

最新更新