【问题标题】:WPF RichTextBox bolding of Text From Code EfficientlyWPF RichTextBox 有效地将代码中的文本加粗
【发布时间】:2012-05-12 06:46:59
【问题描述】:

我是 WPF 的新手,所以请原谅我的无知,我已经尝试在谷歌上搜索这个问题大约 30 分钟以上,但似乎找不到适合我的场景的简单解决方案。

基本上我正在制作一个从服务器读取一行的 IRC 应用程序,我读取了昵称和消息。并写一行:

<Nick> Message typed...

我希望&lt;Nick&gt; 部分以粗体显示。后来可能是一种颜色。我还看到了一些针对每个循环的示例,但是如果我有 1000 多行并且每次有人键入内容时都执行一个 foreach 循环,那会不会效率不高?

请从 c# 编程方面建议最好/最简单的方法。

这是我的代码:

    private void OnChannelMessage(object sender, IrcEventArgs e)
    {
        if (!txtActivity.Dispatcher.CheckAccess())
        {
            txtActivity.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate()
                  {
                      txtActivity.AppendText(string.Format("<Bold><{0}:{1}></Bold> {2}\n", e.Data.Channel, e.Data.Nick, e.Data.Message));

                      //Paragraph p = new Paragraph();
                      //p.Inlines.Add(new Bold(new Run(string.Format("<{0}> ", e.Data.Nick))));
                      //p.Inlines.Add(new Run(string.Format("{0}\n", e.Data.Message)));
                      //txtActivity.Document.Blocks.Add(p); // problem adds a big space between lines.
                  }
            ));
        }
    }

XAML:

<Grid>
    <RichTextBox Name="txtActivity" VerticalScrollBarVisibility="Auto" Margin="12,12,12,41" BorderThickness="2" FontFamily="Consolas">
        <RichTextBox.Resources>
            <Style TargetType="{x:Type Paragraph}">
                <Setter Property="Margin" Value="0"/>
            </Style>
        </RichTextBox.Resources>
    </RichTextBox>
    <Button Content="Quit" Height="23" HorizontalAlignment="Left" Margin="628,371,0,0" Name="btnQuit" VerticalAlignment="Top" Width="50" Click="btnQuit_Click" />
</Grid>

【问题讨论】:

    标签: c# wpf formatting richtextbox


    【解决方案1】:

    使用 FlowDocument。它支持具有大量格式的标记。

    FlowDocument

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-27
      • 2021-07-31
      • 1970-01-01
      • 1970-01-01
      • 2015-12-01
      • 2014-11-02
      • 2015-11-12
      相关资源
      最近更新 更多