Reputation: 19
I am redoing my Windows Forms app in WPF and I am having some trouble with the Selections of Windows Forms and the TextRange of WPF. In Windows Forms, I used to do a Selection of Length 0 on a RichTextBox to change the color of a specific position so that when someone writes starting there it has a different color, withuot changing the color of any text. Something like this:
richTextBox.Select(position, 0);
richTextBox.SelectionColor = Color.Blue;
The problem is that in WPF I can't find any equivalent. If I use a TextRange of Length 0, it does nothing. Do you know what can I do? Thank you!
Upvotes: 0
Views: 140
Reputation: 189
You can try this aproach. It is not good but does it's work.
Brush MyBrush = new SolidColorBrush(Colors.Black);
private void Button_Click(object sender, RoutedEventArgs e)
{
MyBrush = new SolidColorBrush(Colors.Red);
MyRichTextBox.Focus();
}
private void MyRichTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
var textBox = (RichTextBox)sender;
var docStart = textBox.Document.ContentStart.DocumentStart;
foreach (var change in e.Changes)
{
var changeStart = docStart.GetPositionAtOffset(change.Offset, LogicalDirection.Forward);
var changeEnd = docStart.GetPositionAtOffset(change.Offset + change.AddedLength, LogicalDirection.Forward);
var changedRange = new TextRange(changeStart, changeEnd);
changedRange.ApplyPropertyValue(TextElement.ForegroundProperty, MyBrush);
}
}
Upvotes: 1