'Background' 属性 对文本格式无效
'Background' property is not valid for text formatting
我使用的是标准 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);
正如其他 Whosebug 问题提到的那样,我正在使用 System.Windows.Media
命名空间画笔。
编辑:
有趣的是,即使 获取 背景颜色也会引发此错误:
// SUCCESS
var f = this.rtfDocument.Selection.GetPropertyValue(
System.Windows.Controls.RichTextBox.ForegroundProperty);
// ERROR
var b = this.rtfDocument.Selection.GetPropertyValue(
System.Windows.Controls.RichTextBox.BackgroundProperty);
也许错误与实际的 属性 本身有关?
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);
我使用的是标准 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);
正如其他 Whosebug 问题提到的那样,我正在使用 System.Windows.Media
命名空间画笔。
编辑:
有趣的是,即使 获取 背景颜色也会引发此错误:
// SUCCESS
var f = this.rtfDocument.Selection.GetPropertyValue(
System.Windows.Controls.RichTextBox.ForegroundProperty);
// ERROR
var b = this.rtfDocument.Selection.GetPropertyValue(
System.Windows.Controls.RichTextBox.BackgroundProperty);
也许错误与实际的 属性 本身有关?
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);