我有RichTextBox和Button,当在RichTextBox方法中选择文本时,Button_Click会更改文本前景色,但是当所选文本为空时,当我在RichTextBox中添加新文本时,前景色不会改变。前景色仍然相同。
查看
<StackPanel Margin="10">
<Button Height="50" Content="Set Color" Click="Button_Click"/>
<RichTextBox x:Name="richTextBox" Height="198" />
</StackPanel>
代码隐藏
private void Button_Click(object sender, RoutedEventArgs e)
{
if (!richTextBox.Selection.IsEmpty)
{
//selection isn't empty foreground changed
richTextBox.Selection.ApplyPropertyValue(RichTextBox.ForegroundProperty, RandomColor());
}
else
{
//here code when selection text in richtextbox is empty????
}
richTextBox.Focus();
}
private Brush RandomColor()
{
Brush[] brushes = new Brush[]{
Brushes.Red,Brushes.Pink,Brushes.Blue,Brushes.Green,Brushes.Yellow
};
Random rnd = new Random();
return brushes[rnd.Next(brushes.Length)];
}
答案 0 :(得分:1)
您需要在Run
:
FlowDocument
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
var newRun = new Run(string.Empty, MyRichTextBox.CaretPosition.GetInsertionPosition(LogicalDirection.Forward)) { Foreground = Brushes.Red };
MyRichTextBox.CaretPosition.Paragraph.Inlines.Add(newRun);
MyRichTextBox.CaretPosition = newRun.ContentEnd;
MyRichTextBox.Focus();
}