文本框的文字颜色变化(textbox text color change)

2019-07-17 16:51发布

我有textbox textbox1 ,我想改变文字的颜色,但在所有文本的一部分。 例如从/**/就像在Visual Studio评论?

我怎样才能做到这一点?

Answer 1:

试试这个:

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



Answer 2:

你可以这样做,但是,您可能想看看到RichTextBox控制它在哪里很容易做。

简单的例子:

richtextbox.SelectionFont = new Font("Verdana", 10, FontStyle.Regular);
richtextbox.SelectionColor = Color.Blue;


Answer 3:

您必须获得从控制TextBox ,放在代码,要么允许用户改变颜色或者基于您的规则的颜色。

一个RichTextBox会给你此基础上,因为它允许不同的文本的“运行”每一种都可以有它自己的风格:

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

如果你添加控件的颜色等,那么你可以创建一个从用户与所需的样式选择新的运行。



文章来源: textbox text color change
标签: c# wpf textbox