简体   繁体   中英

How to get one character from RichTextBox C# WPF click a button and change the color of it

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM