C# WPF:在字符检测时更改文本颜色

C# WPF: Changing color of Text upon Character Detection

我正在为用户编写一个控制台,以便他们可以在其中编写类似于 Visual Studio 的代码。我想知道如何在程序检测到某个字符的输入时立即更改 WPF TextBox 中一组文本的颜色,例如 /* */ 注释标记。

当用户输入 /* 标签时,标签后的文本应为绿色,当用户关闭标签时,文本应变回白色。我尝试使用 TextChanged 方法执行此操作,但我不知道如何继续。

('console' 是我 Window 中的文本框)

private void console_TextChanged(object sender, TextChangedEventArgs e)
{
      if (e.Changes.Equals("/*"))
      {
             console.Foreground = Brushes.Green;
      }
}

您不能使用 TextBox 更改某些特定部分的颜色。在这种情况下,您需要 RichTextBox。您使用 PreviewTextInput 事件获取键入的 text/char。我已经编写了一些逻辑来在键入特定字符时使 RichTextBox 的前景发生变化。我认为您可以在此代码之上构建您的逻辑。

 <RichTextBox x:Name="rtb" Width="200" Height="200" PreviewTextInput="rtb_PreviewTextInput"/>

 public partial class MainWindow : Window
{
    string prevText=string.Empty;
    TextPointer start;
    public MainWindow()
    {
        InitializeComponent();            
    }      
    private void rtb_PreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        if (e.Text.Equals("*") && (prevText.Equals("/")))
        {
            start = rtb.CaretPosition;
            TextPointer end = rtb.Document.ContentEnd;
            TextRange range = new TextRange(start, end);
            range.ApplyPropertyValue(RichTextBox.ForegroundProperty, Brushes.Green);
        }
        if (e.Text.Equals("/") && (prevText.Equals("*")))
        {                
            TextPointer end = rtb.CaretPosition; 
            TextRange range = new TextRange(start, end);
            range.ApplyPropertyValue(RichTextBox.ForegroundProperty, Brushes.Red);
        }
        prevText = e.Text;
    }        
}