2017-09-30 11 views
1

J'utilise le contrôle WPF standard RichTextBox.La propriété 'Background' n'est pas valide pour le formatage du texte

Je peux définir la couleur de premier plan avec succès, mais le réglage de la couleur de fond donne l'erreur suivante:

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

Voici le code que je teste avec:

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

J'utilise le System.Windows.Media brosses d'espace de noms comme d'autres questions Stackoverflow mentionnent.

EDIT:

Fait intéressant, même obtenir la couleur de fond jette cette erreur:

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

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

Peut-être que l'erreur est de faire avec la propriété réelle elle-même en quelque sorte?

Répondre

2

La méthode TextRange.ApplyPropertyValue applique des valeurs de propriété aux éléments de document, pas à RichTextBox lui-même.

Alors ne propriétés RichTextBox pas défini, mais les propriétés TextElement au lieu:

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