Domanda

I've searched for a while for this solution, so now I'm posting here.

Right now I am able to change the foreground color of the whole RichTextBox:

yourRichTextBox.Foreground = Brushes.Red;

I'm also able to change the color of some text that a user has selected with their cursor:

if(!yourRichTextBox.Selection.IsEmpty){
    yourRichTextBox.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
}

But I want to be able to change the color of the next text that the user types.

I have a color picker box that returns the color a user wants the text to be in. So the user is typing in the RichTextBox in normal black font, then they would click the color picker button, select a color, hit OK and then the next thing they type will be in that color. Is there a way to do this or am I out of luck?

The only way I can think to do it is to have a buffer that captures each character the user types, and then set the foreground property on each letter typed and then add it back into RichTextBox, ideas?

È stato utile?

Soluzione

The same code that you are using for your Selection works for me. For example:

    <RichTextBox x:Name="yourRichTextBox" TextChanged="yourRichTextBox_TextChanged_1">
        <FlowDocument>
            <Paragraph>
                <Run Text="fdsfdfsda"/>
            </Paragraph>
            <Paragraph>
                <Run/>
            </Paragraph>
        </FlowDocument>
    </RichTextBox>

Code Behind:

    private void yourRichTextBox_TextChanged_1(object sender, TextChangedEventArgs e)
    {
        yourRichTextBox.Selection.ApplyPropertyValue(RichTextBox.ForegroundProperty, Brushes.Red);
    }

Once you start typing, the second letter and onward (the first triggers this change) will be red.

Altri suggerimenti

I have another solution that might be interesting. The key is to use the Document property of the RichTextBox.

private void Print(string s)
{
    if (s != null)
    {
        var paragraph = new Paragraph();
        paragraph.Inlines.Add(new Bold(new Run($"{DateTime.Now:HH:mm:ss.fff}: ")) { Foreground = Brushes.Green });
        paragraph.Inlines.Add(new Run($"{(s.EndsWith(Environment.NewLine) ? s : s + Environment.NewLine)}"));
        LogView.Document.Blocks.Add(paragraph);
        LogViewScrollViewer.ScrollToEnd();
    }
}

Xaml:

<ScrollViewer x:Name="LogViewScrollViewer">
    <RichTextBox x:Name="LogView" AcceptsReturn="True" IsReadOnly="True">
        <RichTextBox.Resources>
            <Style TargetType="Paragraph">
                <Setter Property="Margin" Value="0" />
            </Style>
        </RichTextBox.Resources>
    </RichTextBox>
</ScrollViewer>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top