如何在WPF .Net Core 3.1中更改RichTextBox中字符串的颜色?

问题描述

我想更改RichTextBox中字符串的颜色。我搜索了它,发现其中大多数是表格。 我在此站点中找到了以下代码,但未更改字符串Color。

 private static TextPointer GetTextPointAt(TextPointer from,int pos){
            TextPointer ret = from;
            int i = 0;

            while ((i < pos) && (ret != null)){
                if ((ret.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.Text) || (ret.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.None))
                    i++;

                if (ret.GetPositionAtOffset(1,LogicalDirection.Forward) == null)
                    return ret;

                ret = ret.GetPositionAtOffset(1,LogicalDirection.Forward);
            }

            return ret;
        }

internal string Select(RichTextBox rtb,int offset,int length,Color color){
            // Get text selection:
            TextSelection textRange = rtb.Selection;

            // Get text starting point:
            TextPointer start = rtb.Document.ContentStart;

            // Get begin and end requested:
            TextPointer startPos = GetTextPointAt(start,offset);
            TextPointer endPos = GetTextPointAt(start,offset + length);

            // New selection of text:
            textRange.Select(startPos,endPos);

            // Apply property to the selection:
            textRange.ApplyPropertyValue(TextElement.BackgroundProperty,new SolidColorBrush(color));

            // Return selection text:
            return rtb.Selection.Text;
        }

这是我在WPF中的第二天。我对此了解不多。

如何将字符串更改为不同的颜色。

例如, 你好,世界 [红蓝] 红色的“ Hello”和蓝色的“ World”。

这是我的XAML模板:

<Window x:Class="Dev_Terminal.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Dev_Terminal"
        mc:Ignorable="d"
        Title="MainWindow" Height="520" Width="800">
    <Canvas Width="800" Background="Black" Margin="0,-41">
        <RichTextBox x:Name="Console"  HorizontalAlignment="Stretch"   HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible"  Width="710" Height="476" Canvas.Left="63" Background="#FF354657" Foreground="White" FontFamily="Consolas" Grid.IsSharedSizeScope="True" ScrollViewer.CanContentScroll="True" AcceptsTab="True"/>
        <Button Content="Open" Canvas.Left="563" Canvas.Top="481" Height="38" Width="75" RenderTransformOrigin="-0.216,0.633" Click="Open_Click"/>
        <Button Content="Exit" Canvas.Left="663" Canvas.Top="481" Height="38" Width="75" RenderTransformOrigin="-0.216,0.633" Click="Exit_Click" />

    </Canvas>
</Window>

谢谢。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)