WPF RichTextBox-цвет переднего плана из текущей позиции каретки, когда выделение пусто

У меня есть RichTextBox и Button, когда текст выбран в RichTextBox, метод Button_Click меняет цвет текста на переднем плане, но когда выделенный текст пуст, цвет переднего плана не меняется, когда я добавляю новый текст в RichTextBox. Цвет переднего плана остается прежним.

Посмотреть

<StackPanel Margin="10">
        <Button Height="50" Content="Set Color" Click="Button_Click"/>
        <RichTextBox x:Name="richTextBox" Height="198" />
</StackPanel>

Code-Behind

private void Button_Click(object sender, RoutedEventArgs e)
{

        if (!richTextBox.Selection.IsEmpty)
        {
            //selection isn't empty foreground changed
            richTextBox.Selection.ApplyPropertyValue(RichTextBox.ForegroundProperty, RandomColor());
        }
        else
        {
            //here code when selection text in richtextbox is empty????
        }
        richTextBox.Focus();
 }

private Brush RandomColor()
{
        Brush[] brushes = new Brush[]{
            Brushes.Red,Brushes.Pink,Brushes.Blue,Brushes.Green,Brushes.Yellow
        };
        Random rnd = new Random();
        return brushes[rnd.Next(brushes.Length)];

 }

1 ответ

Вам нужно начать новый Run в пределах FlowDocument:

private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
    var newRun = new Run(string.Empty, MyRichTextBox.CaretPosition.GetInsertionPosition(LogicalDirection.Forward)) { Foreground = Brushes.Red };
    MyRichTextBox.CaretPosition.Paragraph.Inlines.Add(newRun);
    MyRichTextBox.CaretPosition = newRun.ContentEnd;
    MyRichTextBox.Focus();
}
Другие вопросы по тегам