简体   繁体   中英

textbox text color change

I have textbox textbox1 and I want to change text color, but in the part of all text. For example from /* to */ like comments in visual studio?

How I can do this?

Try this one:

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

or this:

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;

Source:

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

And MSDN:

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

You can do this, however, you may want to look into the RichTextBox control where is it much easier to do.

Simple example:

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

You will have to derive a control from TextBox and put in code that will either allow the user to change the colour or changes the colour based on your rules.

A RichTextBox will give you the basis for this as it allows different "runs" of text each of which can have it's own styling:

<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM