决定RichTextBox的字体样式(粗体,斜体,下划线)

本文关键字:斜体 下划线 粗体 RichTextBox 字体 样式 决定 | 更新日期: 2023-09-27 18:10:06

如何在RichTextBox中更改字体?

环顾四周,我得到了似乎不再有效的旧答案。我认为这就像做richtextbox1.Font = Font.Bold;或类似的东西一样简单。结果不是,所以我四处看看。显然,你必须改变FontStyle,这是一个readonly(?? ?)属性,但你必须做一个新的FontStyle对象。

但即使这样也不行。o

你是怎么做到的?编辑:

似乎不工作:'

            rssTextBox.Document.Blocks.Clear();
            rssTextBox.FontWeight = FontWeights.Bold;
            rssTextBox.AppendText("Title: ");
            rssTextBox.FontWeight = FontWeights.Normal;
            rssTextBox.AppendText(rs.Title + "'n");
            rssTextBox.FontWeight = FontWeights.Bold;
            rssTextBox.AppendText("Publication Date: ");
            rssTextBox.FontWeight = FontWeights.Normal;
            rssTextBox.AppendText(rs.PublicationDate + "'n");
            rssTextBox.FontWeight = FontWeights.Bold;
            rssTextBox.AppendText("Description: ");
            rssTextBox.FontWeight = FontWeights.Normal;
            rssTextBox.AppendText(rs.Description + "'n'n");

决定RichTextBox的字体样式(粗体,斜体,下划线)

BoldFontWeight。你可以直接使用

如MSDN文档所述"获取或设置指定字体的粗细。"

可以在xaml

中设置
<RichTextBox FontWeight="Bold" x:Name="richText" />

或在codebehind:

richText.FontWeight = FontWeights.Bold;

如果你想切换FontFamily,那就像:

richText.FontFamily = new FontFamily("Arial");

FontStyle:

richText.FontStyle = FontStyles.Italic;

Update:(用于更新RichTextBox inline)

这只是一个快速的模型。以这个为例。请根据您的要求组织。

richText.Document.Blocks.Clear();
Paragraph textParagraph = new Paragraph();
AddInLineBoldText("Title: ", ref textParagraph);
AddNormalTextWithBreak(rs.Title, ref textParagraph);
AddInLineBoldText("Publication Date: ", ref textParagraph);
AddNormalTextWithBreak(rs.PublicationDate, ref textParagraph);
AddInLineBoldText("Description: ", ref textParagraph);
AddNormalTextWithBreak(rs.Description, ref textParagraph);
AddNormalTextWithBreak("", ref textParagraph);
richText.Document.Blocks.Add(textParagraph);
private static void AddInLineBoldText(string text, ref Paragraph paragraph) {
  Bold myBold = new Bold();
  myBold.Inlines.Add(text);
  paragraph.Inlines.Add(myBold);
}
private static void AddNormalTextWithBreak(string text, ref Paragraph paragraph) {
  Run myRun = new Run {Text = text + Environment.NewLine};
  paragraph.Inlines.Add(myRun);
}