テキストの色を変更したい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>
色などのコントロールを追加すると、必要なスタイルでユーザーの選択から新しいランを作成できます。