WPF RichTextBox - 选择为空时从当前插入符号位置开始的前景色

时间:2015-08-03 15:54:43

标签: wpf selection richtextbox foreground is-empty

我有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>

代码隐藏

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 个答案:

答案 0 :(得分: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();
}