仅包含颜色的 WPF 文本控件

Огњ*_*јић 2 wpf textbox colors richtextbox

我需要一个文本控件,用户可以在其中编辑文本,并且文本的某些部分可以根据文本具有不同的颜色。基本上,想象一下 Visual Studio 源文件编辑器或任何其他为源代码着色的源文件编辑器。那是什么WPF控件?据我所知,WPF 中的三个选项都不适合:

文本框不允许使用颜色

TextBlock不允许用户编辑文本

RichTextBox允许太多 - 我只想要颜色。

也许 RichTextBox 可以修复其他文本格式(即字体、粗体、斜体)?有什么想法吗?

Mar*_*ari 5

这是一个(非常)粗略的示例,坚持使用 TextBox 和 TextBlock:只是为了好玩,但值得......

在此输入图像描述

这是 XAML...

<Grid>
    <TextBlock
        x:Name="Tx1"
        HorizontalAlignment="{Binding Path=HorizontalAlignment, ElementName=Tb1}"
        VerticalAlignment="{Binding Path=VerticalAlignment, ElementName=Tb1}"
        Margin="{Binding Path=Margin, ElementName=Tb1}"
        FontSize="{Binding Path=FontSize, ElementName=Tb1}"
        />

    <TextBox
        x:Name="Tb1"
        HorizontalAlignment="Stretch"
        VerticalAlignment="Center"
        Margin="100,0"
        FontSize="24"
        Background="Transparent"
        Foreground="Transparent"
        TextChanged="Tb1_TextChanged"
        />
</Grid>
Run Code Online (Sandbox Code Playgroud)

...这是一些代码...

    private void Tb1_TextChanged(object sender, TextChangedEventArgs e)
    {
        var inlines = this.Tx1.Inlines;
        inlines.Clear();

        foreach (char ch in this.Tb1.Text)
        {
            if (Char.IsDigit(ch))
            {
                var run = new Run(ch.ToString());
                run.Foreground = Brushes.Blue;
                inlines.Add(run);
            }
            else if (Char.IsLetter(ch))
            {
                var run = new Run(ch.ToString());
                run.Foreground = Brushes.Red;
                inlines.Add(run);
            }
            else
            {
                var run = new Run(ch.ToString());
                run.Foreground = Brushes.LimeGreen;
                inlines.Add(run);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

诀窍是在TextBlock上使用透明的 TextBox,可以通过收集许多不同的 Run 元素来为其着色。