如何在richtextbox WPF中使用多色

wlzqhblo  于 2023-10-22  发布在  其他
关注(0)|答案(2)|浏览(238)

我使用C# WPF,我有richtextbox,我想把一些文本涂成红色,一些涂成绿色,一些涂成黑色。如何做到这一点?

dz6r00yl

dz6r00yl1#

在RichTextBox中使用FlowDocumentReader。因此,您可以使用文档类:List、Paragraph、Section、Table、LineBreak、Figure、Floater和Span,并更改它们的属性:

<FlowDocumentReader x:Name="myDocumentReader" Height="269.4">
<FlowDocument>
<Section Foreground = "Yellow" Background = "Black">
<Paragraph FontSize = "20">
Here are some fun facts about the WPF Documents API!
</Paragraph>
</Section>
<List x:Name="listOfFunFacts"/>
<Paragraph x:Name="paraBodyText"/>
</FlowDocument>
</FlowDocumentReader>

您还可以填充和更改属性,例如,在代码中的List right:

this.listOfFunFacts.Foreground = Brushes.Brown;
this.listOfFunFacts.FontSize = 14;
this.listOfFunFacts.MarkerStyle = TextMarkerStyle.Circle;
this.listOfFunFacts.ListItems.Add(new ListItem( new Paragraph(new Run("Sample Text"))));
3zwtqj6y

3zwtqj6y2#

我需要一个“简单”的文本框,每行不同的颜色,使用MVVM。我找到的所有答案都是关于RichTextBox文档的,对于我的需求来说太复杂了,所以我发布了这个答案:
XAML

<RichTextBox>
    <FlowDocument>
        <components:BindableParagraph InlineList="{Binding Messages}" />
    </FlowDocument>
</RichTextBox>

BindableParagraph

internal class BindableParagraph : Paragraph
{
    public ObservableCollection<Inline> InlineList
    {
        get { return (ObservableCollection<Inline>)GetValue(InlineListProperty); }
        set { SetValue(InlineListProperty, value); }
    }
    
    public static readonly DependencyProperty InlineListProperty =
        DependencyProperty.Register("InlineList", typeof(ObservableCollection<Inline>), typeof(BindableParagraph), new UIPropertyMetadata(null, OnPropertyChanged));

    private static void OnPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        BindableParagraph textBlock = sender as BindableParagraph;
        ObservableCollection<Inline> list = e.NewValue as ObservableCollection<Inline>;
        list.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(textBlock.InlineCollectionChanged);
    }

    private void InlineCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
        {
            int idx = e.NewItems.Count - 1;
            Inline inline = e.NewItems[idx] as Inline;
            this.Inlines.Add(inline);
        }
    }
}

VM

private ObservableCollection<Inline> _messages;
public ObservableCollection<Inline> Messages
{
    get { return _messages; }
    set { SetProperty(ref _messages, value); }
}

private void AddMessage(string message, MessageLevel messageLevel = MessageLevel.None)
{
    Messages.Add(new Run()
    {
        Foreground = messageLevel == MessageLevel.Error ? Brushes.Red : Brushes.Black,
        Text = message + Environment.NewLine,
    });
}

相关问题