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.
<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>
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();
}