我有textbox
textbox1
并且我想更改文本颜色,但在所有文本的一部分。例如从/*
到*/
喜欢视觉工作室中的评论?
我怎么能做到这一点?
试试这个:
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;
来源:
和 MSDN:
http://msdn.microsoft.com/en-us/library/system.windows.controls.richtextbox.document.aspx
您可以这样做,但是,您可能想要查看 RichTextBox 控件,哪里更容易做到。
简单的例子:
richtextbox.SelectionFont = new Font("Verdana", 10, FontStyle.Regular);
richtextbox.SelectionColor = Color.Blue;
您必须从中派生控件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.