[英]WPF RichTextBox change font color inline
我已經搜索了一段時間來尋找這個解決方案,所以現在我在這里發帖。
現在我可以改變整個RichTextBox
的前景色:
yourRichTextBox.Foreground = Brushes.Red;
我還可以更改用戶使用光標選擇的某些文本的顏色:
if(!yourRichTextBox.Selection.IsEmpty){
yourRichTextBox.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
}
但我希望能夠更改用戶鍵入的下一個文本的顏色。
我有一個顏色選擇器框,它返回用戶希望文本所在的顏色。所以用戶在RichTextBox
中輸入普通黑色字體,然后他們會點擊顏色選擇器按鈕,選擇一種顏色,點擊確定,然后他們輸入的下一件事將是那種顏色。 有沒有辦法做到這一點,還是我運氣不好?
我能想到的唯一方法是有一個緩沖區來捕獲用戶鍵入的每個字符,然后在鍵入的每個字母上設置前景屬性,然后將其添加回RichTextBox
,想法?
您用於選擇的代碼與我相同。 例如:
<RichTextBox x:Name="yourRichTextBox" TextChanged="yourRichTextBox_TextChanged_1">
<FlowDocument>
<Paragraph>
<Run Text="fdsfdfsda"/>
</Paragraph>
<Paragraph>
<Run/>
</Paragraph>
</FlowDocument>
</RichTextBox>
背后的代碼:
private void yourRichTextBox_TextChanged_1(object sender, TextChangedEventArgs e)
{
yourRichTextBox.Selection.ApplyPropertyValue(RichTextBox.ForegroundProperty, Brushes.Red);
}
開始輸入后,第二個字母及以上(第一個字母觸發此更改)將為紅色。
我有另一個可能很有趣的解決方案。 關鍵是使用 RichTextBox 的 Document 屬性。
private void Print(string s)
{
if (s != null)
{
var paragraph = new Paragraph();
paragraph.Inlines.Add(new Bold(new Run($"{DateTime.Now:HH:mm:ss.fff}: ")) { Foreground = Brushes.Green });
paragraph.Inlines.Add(new Run($"{(s.EndsWith(Environment.NewLine) ? s : s + Environment.NewLine)}"));
LogView.Document.Blocks.Add(paragraph);
LogViewScrollViewer.ScrollToEnd();
}
}
Xml:
<ScrollViewer x:Name="LogViewScrollViewer">
<RichTextBox x:Name="LogView" AcceptsReturn="True" IsReadOnly="True">
<RichTextBox.Resources>
<Style TargetType="Paragraph">
<Setter Property="Margin" Value="0" />
</Style>
</RichTextBox.Resources>
</RichTextBox>
</ScrollViewer>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.