我有一个 WPF .NET 4 C# RichTextBox
,我想用其他字符替换该文本框中的某些字符,这发生在 KeyUp
上事件。
我想要实现的是用完整的单词替换首字母缩略词,例如:
pc = 个人电脑
sc =星际争霸
等...
我查看了一些类似的线程,但我发现的任何内容在我的场景中都没有成功。
最终,我希望能够使用首字母缩略词列表来完成此操作。但是,我什至连替换单个首字母缩略词都遇到了问题,有人可以帮忙吗?
最佳答案
因为 System.Windows.Controls.RichTextBox
没有 Text
的属性要检测其值,您可以使用以下方法检测其值
string _Text = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text;
然后,你可以改变_Text
并使用以下内容发布新字符串
_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;
}
所以,它看起来像这样
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
}
备注:不使用Text.Replace("pc", "Personal Computer");
你可以申报 List<String>
在其中保存字符及其替换
示例:
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");
}
谢谢,
希望对您有所帮助 :)
关于c# - 自动替换wpf richtextbox中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13041350/