Search code examples
c#wpfxamltextblockrichtextblock

WPF - Trying to Append Textblock Texts throws "Object Reference not set to an instance of an object" error


So, I just started using WPF. I'm trying to create a program to speed up the process of making cards. I'm currently struggling trying to append the text of two text blocks into a richtextblock (In order to create the description of a card with its effect and flavor text). WPF says the second textblock is "undefined". Here is my code.

 private void EffectInput_TextChanged(object sender, TextChangedEventArgs e)
        {
            Paragraph effectText = new Paragraph();
            Paragraph flavorText = new Paragraph();

            effectText.Inlines.Add(EffectInput.Text);
            flavorText.Inlines.Add(FlavorInput.Text); //This is the line throwing the error

            Description.Document.Blocks.Clear();

            Description.Document.Blocks.Add(effectText);
           Description.Document.Blocks.Add(flavorText);
        }

I'm new in this, what should I do?


Solution

  • You're in the EffectInput_TextChanged function. You'll have to access the text from FlavorInput another way. You could store it in another variable and just update that variable any time the text changes. I can't remember how to clear the Paragraph object so you'll have to experiment with that part.

    Paragraph flavorText = new Paragraph();
    Paragraph effectText = new Paragraph();
    
    private void FlavorInput_TextChanged(object sender, TextChangedEventArgs e){
       flavorText.Inlines.Clear();
       flavorText.Inlines.Add(FlavorInput.Text);
       updateBlocks();
    }
    
    private void EffectInput_TextChanged(object sender, TextChangedEventArgs e)
    {
       effectText.Inlines.Clear();
       effectText.Inlines.Add(EffectInput.Text);
       updateBlocks();
    }
    
    private void updateBlocks(){
       Description.Document.Blocks.Clear();
       Description.Document.Blocks.Add(effectText);           
       Description.Document.Blocks.Add(flavorText);     
    }