设置WPF的Textblock.Text属性会抛出NullReferenceException

Mas*_*tic 0 c# wpf text textblock

textBlock.Text = "Text";
Run Code Online (Sandbox Code Playgroud)

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

Object reference not set to an instance of an object.
Run Code Online (Sandbox Code Playgroud)

这个语句在Slider的ValueChanged事件中,如果重要的话.

Dan*_*rth 7

我假设此代码在您的构造函数中.确保InitializeComponents在执行此行之前调用:

public YourWindow()
{
    TextBlock.Text = "Text"; // <- bad
    InitializeComponents();
    TextBlock.Text = "Text"; // <- good
}
Run Code Online (Sandbox Code Playgroud)