7

我有textbox textbox1并且我想更改文本颜色,但在所有文本的一部分。例如从/**/喜欢视觉工作室中的评论?

我怎么能做到这一点?

4

3 回答 3

5

试试这个:

TextRange rangeOfText1 = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd);
rangeOfText1.Text = "Text1 ";
rangeOfText1.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);
rangeOfText1.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);

TextRange rangeOfWord = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd);
rangeOfWord.Text = "word ";
rangeOfWord.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
rangeOfWord.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Regular);

TextRange rangeOfText2 = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd);
rangeOfText2.Text = "Text2 ";
rangeOfText2.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);
rangeOfText2.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);

或这个:

public TestWindow()
{
InitializeComponent();

this.paragraph = new Paragraph();
rich1.Document = new FlowDocument(paragraph);

var from = "user1";
var text = "chat message goes here";
paragraph.Inlines.Add(new Bold(new Run(from + ": "))
{
    Foreground = Brushes.Red
});
paragraph.Inlines.Add(text);
paragraph.Inlines.Add(new LineBreak());
this.DataContext = this;
}
private Paragraph paragraph;

来源:

在 WPF C# 中更改部分文本的颜色和字体

和 MSDN:

http://msdn.microsoft.com/en-us/library/system.windows.controls.richtextbox.document.aspx

于 2012-12-29T20:39:34.760 回答
0

您可以这样做,但是,您可能想要查看 RichTextBox 控件,哪里更容易做到。

简单的例子:

richtextbox.SelectionFont = new Font("Verdana", 10, FontStyle.Regular);
richtextbox.SelectionColor = Color.Blue;
于 2012-12-29T20:24:26.533 回答
0

您必须从中派生控件TextBox并放入代码,以允许用户更改颜色或根据您的规则更改颜色。

ARichTextBox将为您提供基础,因为它允许不同的文本“运行”,每个文本都可以有自己的样式:

<RichTextBox Name="richTB">
  <FlowDocument>
    <Paragraph>
      <Run>Paragraph 1</Run>
    </Paragraph>
    <Paragraph>
      <Run>Paragraph 2</Run>
    </Paragraph>
    <Paragraph>
      <Run>Paragraph 3</Run>
    </Paragraph>
  </FlowDocument>
</RichTextBox>

If you add controls for colour etc. then you can create a new run from the user's selection with the required style.

于 2012-12-29T20:41:28.413 回答