wpf - RichTextBox - TextRanges 之间的换行符

标签 wpf richtextbox

我在使用 RichTextBox 时遇到了一个小问题。

我正在尝试进行某种聊天,包括每行不同的颜色,这就是我使用 RichTextBox 而不是普通文本框的原因。但是我在换行时遇到了一些麻烦。

我的目标是实现这种格式:

Player 1: Hello world!
System Bot: The game has begun!
Player 2: sup man?
Player 1: Nothing

不幸的是,我的代码到目前为止还没有完成它的工作:

public void Handle(NewMessageMessage message)
{
    var messageStr = message.Message;

    var range = new TextRange(ChatMessages.ContentEnd, ChatMessages.ContentEnd);

    switch (message.Type)
    {
        case MessageType.SystemInformation:
            range.Text = string.Concat("System-Bot: ", messageStr, "\r\n");
            range.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Color.FromArgb(255, 255, 150, 0)));
            break;
        case MessageType.SystemWarning:
            range.Text = string.Concat("System-Bot: ", messageStr, "\r\n");
            range.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
            break;
        case MessageType.PlayerMessage:
            range.Text = string.Concat(messageStr, "\r\n");
            range.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);
            break;
    }

    NotifyOfPropertyChange(() => ChatMessages);

    TriggerScrollViewerScroll = true;
}

代码没有给我预期的结果:

Player 1: Hello world!System Bot: The game has begun!

Player 2: sup man?

Player 1: Nothing

省略\r\n 给我这个:

Player 1: Hello world!System Bot: The game has begun!Player 2: sup man?Player 1: Nothing

我的 RichTextBox 看起来像这样:

<controls:ChatRichTextBox Document="{Binding ChatMessages}"  IsReadOnly="True" Margin="5"/>

有人知道那里发生了什么吗?

最佳答案

您可以使用“\r”代替“\r\n”。

问题出在“\r\n”,它表示一个新段落。默认情况下,段落在 RichTextBox 中有边距。如果将段落的边距设置为 0,则“\r\n”将起作用(或者 Environment.NewLine 也将起作用)。 在你的 xaml 中设置像这样的边距:

 <Window.Resources>
        <Style TargetType="{x:Type Paragraph}">
            <Setter Property="Margin"
                    Value="0" />
        </Style>
    </Window.Resources>

关于wpf - RichTextBox - TextRanges 之间的换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27470108/

相关文章:

c# - 自定义 RichTextBox OnKeyDown 覆盖不起作用

c# - 将 Drawing.Bitmap 转换为 Imaging.Metafile - Pixel Perfect

c# - 同步两个 RichTextBox 的滚动位置?

c# - 在 RichtextBox 中为文本着色,C#

wpf - 使用 C# 在 WPF 中使 DataGrid 列标题可排序

.net - 在 .NET 中创建内部 XAML 文件

c# - 如何将图像分成 9 block 并随机放置在 Canvas 中?

xaml - 如何使 RichTextBlock 中的超链接不完全不对齐?

c# - WPF JumpTask 另一个图标不是默认图标吗?

wpf - wpf动态数据展示中如何高亮标注指定点?