2017-09-30 45 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);