'背景'属性对文本格式无效

时间:2017-09-30 08:49:58

标签: wpf richtextbox

我使用的是标准WPF RichTextBox控件。

我可以成功设置前景色,但设置背景色会产生以下错误:

  

System.ArgumentException:''背景'属性对文本格式无效。'

以下是我测试的代码:

// SUCCESS
this.rtfDocument.Selection.ApplyPropertyValue(
    System.Windows.Controls.RichTextBox.ForegroundProperty,
    System.Windows.Media.Brushes.Red);

// ERROR
this.rtfDocument.Selection.ApplyPropertyValue(
    System.Windows.Controls.RichTextBox.BackgroundProperty,
    System.Windows.Media.Brushes.Blue);

我正在使用System.Windows.Media命名空间画笔,因为其他Stackoverflow问题会提到。

修改

有趣的是,即使获取背景颜色也会引发此错误:

// SUCCESS
var f = this.rtfDocument.Selection.GetPropertyValue(
    System.Windows.Controls.RichTextBox.ForegroundProperty);

// ERROR
var b = this.rtfDocument.Selection.GetPropertyValue(
    System.Windows.Controls.RichTextBox.BackgroundProperty);

也许错误是以某种方式与实际属性本身有关?

1 个答案:

答案 0 :(得分:2)

TextRange.ApplyPropertyValue方法将属性值应用于文档元素,而不是RichTextBox本身。

所以不要设置RichTextBox属性,而是设置TextElement属性:

rtfDocument.Selection.ApplyPropertyValue(
    System.Windows.Documents.TextElement.ForegroundProperty,
    System.Windows.Media.Brushes.Red);

rtfDocument.Selection.ApplyPropertyValue(
    System.Windows.Documents.TextElement.BackgroundProperty,
    System.Windows.Media.Brushes.Blue);
相关问题