Reputation: 118
I have a RichTextBox
and a button. I want to get one char from the RichTextBox
and change the color of it every time when user click the button.
I read a lot about TextRange
but I can't do it in the right way.
var textentered = txtuser.Text.Substring(txtuser.SelectionStart-1, 1);
var tmptext = txtprogramtext.Substring(txtuser.SelectionStart-1, 1 );
var rangeOfText1 = new TextRange(txtprogram.CaretPosition.GetNextContextPosition(LogicalDirection.Forward),
txtprogram.CaretPosition.GetNextContextPosition(LogicalDirection.Forward));
Upvotes: 0
Views: 399
Reputation: 8915
The following code fragment colors one character in the RichTextBox
from the current caret position:
private void Button_Click(object sender, RoutedEventArgs e)
{
// Case 1: Color one character from the current caret position
var startPosition = rtb.CaretPosition;
// Forward to next character
var endPosition = rtb.CaretPosition.GetPositionAtOffset(1, LogicalDirection.Forward);
var tr = new TextRange(startPosition, endPosition);
tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
rtb.CaretPosition = endPosition; // Forward the caret
//// Case 2: The following line will color the current selected text
//rtb.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
}
The XAML:
<Window ... >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<RichTextBox Grid.Row="0" x:Name="rtb" AllowDrop="True" VerticalScrollBarVisibility="Auto" Padding="2">
<FlowDocument>
<Paragraph FontSize="12" TextAlignment="Left">
<Paragraph.Foreground>
<SolidColorBrush Color="Blue"/>
</Paragraph.Foreground>
<Run Text="RichTextBox has built-in handling for the bubbling MouseUp and MouseDown events. " />
</Paragraph>
<Paragraph FontSize="12" TextAlignment="Left" >
<Paragraph.Foreground>
<SolidColorBrush Color="Black"/>
</Paragraph.Foreground>
<Run Text="If you need to respond to these events, listen for the tunneling PreviewMouseUp and PreviewMouseDown events instead..." />
</Paragraph>
</FlowDocument>
</RichTextBox>
<Button Grid.Row="1" Click="Button_Click">Color</Button>
</Grid>
</Window>
Upvotes: 2