I have a WPF .NET 4 C# RichTextBox
and I'm wanting to replace certain characters within that text box with other characters, this is to happen on the KeyUp
event.
What I'm trying to achieve is replace acronyms with full words, e.g.:
pc = personal computer
sc = starcraft
etc...
I've looked a few similar threads, but anything I've found hasn't been successful in my scenario.
Ultimately, I'd like to be able to do this with a list of acronyms. However, I'm having issues with even replacing a single acronym, can anyone help?
Because System.Windows.Controls.RichTextBox
does not have a property for Text
to detect its value, you may detect its value using the following
string _Text = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text;
Then, you may change _Text
and post the new string 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'd look like this
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
}
Remark: Instead of using Text.Replace("pc", "Personal Computer");
you may declare a List<String>
in which you save the characters and its 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,
I hope you find this helpful :)