Click here to Skip to main content
15,878,852 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
Hi guys,

I'm trying to get this little app to colour text that is selected when a button is pressed, or colour anything that comes after the caret when typing if nothing is selected.

This works, but I have a bug where, if I insert the caret between two characters and press a button, EVERYTHING is coloured. I do not want this, just everything that comes after the caret.

My assumption is that 'rtb.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, colour);' is assuming everything on either side of it is 'selected'.

Can anyone assist, perhaps?

Thank you in advance.

XML
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="300" Width="400">
    <Grid removed="Gray">
        <RichTextBox removed="Black" Foreground="White" Height="150" HorizontalAlignment="Right" Name="rtb" VerticalAlignment="Top" Width="354" Margin="0,12,12,0" />
        <Button Background="Blue" Content="Blue" Height="75" HorizontalAlignment="Left" Margin="139,174,0,0" Name="button2" VerticalAlignment="Top" Width="100" Click="btnColour_Click" Foreground="Yellow" />
        <Button Background="Red" Content="Red" Height="75" HorizontalAlignment="Left" Margin="12,174,0,0" Name="button1" VerticalAlignment="Top" Width="100" Click="btnColour_Click" Foreground="Blue" />
        <Button Background="Yellow" Content="Green" Height="75" HorizontalAlignment="Left" Margin="266,174,0,0" Name="button3" VerticalAlignment="Top" Width="100" Click="btnColour_Click" Foreground="Red" />
    </Grid>
</Window>


C#
private void colourText(Brush colour)
{

    TextPointer startPointer = rtb.Document.ContentStart.GetNextInsertionPosition(LogicalDirection.Forward);
    TextPointer endPointer = rtb.Document.ContentEnd.GetNextInsertionPosition(LogicalDirection.Backward);
    TextRange range = new TextRange(startPointer, endPointer);
    int length = range.Text.Length;

    rtb.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, colour);

    if (length == 0)
    {
        rtb.Foreground = colour;
    }
}

private void btnColour_Click(object sender, RoutedEventArgs e)
{
    Button btn = sender as Button;
    Brush colour = btn.Background;

    colourText(colour);
    rtb.Focus();
}
Posted

1 solution

It looks like the only way to resolve this I could come up with was to use the OnTexTInput event and have it manually change every letter when typed. I fear for the issues of speed, but so far it seems to work.

(I'll get used to this solution thing one day, maybe!)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900