2017-09-30 21 views
1

我正在使用标准WPF RichTextBox控件。“背景”属性对文本格式无效

我可以成功设置前景色,但设置背景颜色给出了如下错误:

System.ArgumentException: ''Background' property is not valid for text formatting.'

这是我与测试代码:

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

也许误差与实际属性本身以某种方式吗?

回答

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