为RichTextBox确定FontStyle(粗体,斜体,下划线)

时间:2013-04-20 22:34:33

标签: c# wpf richtextbox

您如何更改RichTextBox中的字体?

环顾四周给了我一些似乎不再有用的旧答案。我认为这就像做richtextbox1.Font = Font.Bold;或类似事情一样简单。事实证明不是,所以我环顾四周。显然你必须更改FontStyle readonly(??)属性,但你必须创建一个新的FontStyle对象。

但即便如此,o.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");

1 个答案:

答案 0 :(得分:3)

BoldFontWeight。您可以直接申请。

由于MSDN Doc状态“获取或设置指定字体的重量或厚度。”

您可以在xaml中设置

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

或代码隐藏:

richText.FontWeight = FontWeights.Bold;

如果您尝试切换FontFamily,那将是:

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

FontStyle

richText.FontStyle = FontStyles.Italic;

更新 :(用于更新RichTextBox内联)

这只是一个快速的模型。以此为例。请根据您的要求进行构建。

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);
}