【问题标题】:textbox text color change文本框文本颜色更改
【发布时间】:2012-12-29 20:22:10
【问题描述】:

我有textbox textbox1 我想更改文本颜色,但在所有文本的一部分。例如从 /* 到 */ 就像 Visual Studio 中的 cmets?

我该怎么做?

【问题讨论】:

标签: c# wpf textbox


【解决方案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;

来源:

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

【讨论】:

  • 如何在 RichTextBox.Text 中找到 /* 和 */ 之间的文本?
  • 嗯,那是另一个话题,我知道的就这么多。感谢您的投票和接受。
  • 这不能回答问题!问题专门针对 TextBox,而不是 RichTextBox。
【解决方案2】:

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

简单示例:

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

【讨论】:

【解决方案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>

如果您添加颜色等控件,那么您可以根据用户的选择创建一个具有所需样式的新运行。

【讨论】:

    猜你喜欢
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多