Search code examples
c#wpftextboxtextchanged

C# WPF: Changing color of Text upon Character Detection


I'm writing a Console for users, so that they can write code in it similar to Visual Studio. I was wondering how to change the color of a set of text in a WPF TextBox as soon as the program detects the input of a certain character, such as the /* */ comment tags.

When a user enters a /* tag, the text after the tag should be colored in green and when the users closes the tags, the texts should turn back to white. I tried doing this with the TextChanged method but I don't know how to proceed.

('console' is the TextBox in my Window)

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

Solution

  • You cannot use TextBox to change some specific portion of color. In this case you need RichTextBox. You use the PreviewTextInput event to get the typed text/char. I have written some logic to make the foreground of the RichTextBox change when typing specific char. I think you can build your logic one top of this code.

     <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;
        }        
    }