WPF - 尝试追加文本块文本引发"Object Reference not set to an instance of an object"错误



所以,我刚刚开始使用WPF。我正在尝试创建一个程序来加快制作卡片的过程。我目前正在努力尝试将两个文本块的文本附加到富文本块中(以便创建卡片及其效果和风味文本的描述)。WPF 表示第二个文本块是"未定义的"。这是我的代码。

 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);
        }

我是新手,我该怎么办?

> 你在EffectInput_TextChanged函数中。您必须从FlavorInput另一种方式访问文本。您可以将其存储在另一个变量中,并在文本更改时随时更新该变量。我不记得如何清除Paragraph对象,所以你必须试验该部分。

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);     
}

相关内容

最新更新