Auto replace text in wpf richtextbox

I have WPF.NET 4 C # RichTextBox and I want to replace certain characters in this text box with other characters, this will happen in the KeyUp event.

What I'm trying to achieve is to replace abbreviations with full words, for example:
pc = personal computer
sc = starcraft
etc.

I looked at several similar threads, but everything I found was not successful in my scenario.

Ultimately, I would like to be able to do this with a list of abbreviations. However, I am having problems replacing one abbreviation, can anyone help?

+4
source share
1 answer

Since System.Windows.Controls.RichTextBox does not have a property for Text to determine its value, you can detect its value using the following

 string _Text = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text; 

Then you can change _Text and post a new line using the following

 _Text = _Text.Replace("pc", "Personal Computer"); if (_Text != new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text) { new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text = _Text; } 

So it will look like

 string _Text = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text; _Text = _Text.Replace("pc", "Personal Computer"); // Replace pc with Personal Computer if (_Text != new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text) { new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text = _Text; // Change the current text to _Text } 

Note Instead of using Text.Replace("pc", "Personal Computer"); you can declare a List<String> in which you save the characters and their replacements

Example:

  List<string> _List = new List<string>(); private void richTextBox1_TextChanged(object sender, TextChangedEventArgs e) { string _Text = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text; for (int count = 0; count < _List.Count; count++) { string[] _Split = _List[count].Split(','); //Separate each string in _List[count] based on its index _Text = _Text.Replace(_Split[0], _Split[1]); //Replace the first index with the second index } if (_Text != new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text) { new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text = _Text; } } private void Window_Loaded(object sender, RoutedEventArgs e) { // The comma will be used to separate multiple items _List.Add("pc,Personal Computer"); _List.Add("sc,Star Craft"); } 

Thanks,
Hope you find this helpful :)

+2
source

Source: https://habr.com/ru/post/1441690/