Search code examples
c#wpftexttextblock

Setting WPF's Textblock.Text property throws NullReferenceException


textBlock.Text = "Text";

This is my code, and it shows no errors. but when I run it, I get a NullReferenceException

Object reference not set to an instance of an object.

This statement is inside a ValueChanged event of a Slider, should it matter.


Solution

  • I assume this code is in your constructor. Make sure InitializeComponents is called before you execute this line:

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