文本框文本颜色更改

时间:2012-12-29 20:22:10

标签: c# wpf textbox

我有textbox textbox1我希望更改文字颜色,但在所有文字中。例如,从/**/喜欢在visual studio中发表评论吗?

我怎么能这样做?

3 个答案:

答案 0 :(得分:3)

试试这个:

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;

来源:

Change color and font for some part of text in WPF C#

和MSDN:

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

答案 1 :(得分:0)

您可以这样做,但是,您可能希望查看RichTextBox控件,这样做更容易。

简单示例:

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

答案 2 :(得分:0)

您必须从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>

如果添加颜色等控件,则可以使用所需样式从用户选择中创建新运行。