首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WPF RichTextBox-选择为空时从当前插入符号位置显示的前景色

WPF RichTextBox-选择为空时从当前插入符号位置显示的前景色
EN

Stack Overflow用户
提问于 2015-08-03 15:54:42
回答 1查看 1.6K关注 0票数 0

我有RichTextBox和Button,当在RichTextBox方法Button_Click中选择文本时,Button_Click会更改文本的前景色,但是当选定的文本为空时,当我在RichTextBox中添加新文本时,前景颜色不会改变。前景颜色还是一样的。

视图

代码语言:javascript
复制
<StackPanel Margin="10">
        <Button Height="50" Content="Set Color" Click="Button_Click"/>
        <RichTextBox x:Name="richTextBox" Height="198" />
</StackPanel>

代码-幕后

代码语言:javascript
复制
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)];

 }
EN

回答 1

Stack Overflow用户

发布于 2015-08-03 16:34:53

您需要在Run中启动一个新的FlowDocument

代码语言:javascript
复制
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();
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31791698

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档