Mik*_*Dub 5 c# wpf .net-4.0 richtextbox
我有一个 WPF .NET 4 C# RichTextBox
,我想用其他字符替换该文本框中的某些字符,这将在事件中发生KeyUp
。
我想要实现的目标是用完整的单词替换首字母缩略词,例如:
pc = 个人计算机
sc = 星际争霸
等...
我查看了一些类似的线程,但我发现的任何内容在我的场景中都没有成功。
最终,我希望能够通过首字母缩略词列表来做到这一点。但是,我什至在替换单个缩写词时都遇到问题,有人可以帮忙吗?
由于System.Windows.Controls.RichTextBox
没有用于Text
检测其值的属性,因此您可以使用以下方法检测其值
string _Text = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text;
Run Code Online (Sandbox Code Playgroud)
然后,您可以_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;
}
Run Code Online (Sandbox Code Playgroud)
所以,它看起来像这样
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
}
Run Code Online (Sandbox Code Playgroud)
备注Text.Replace("pc", "Personal Computer");
:您可以声明 aList<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");
}
Run Code Online (Sandbox Code Playgroud)
谢谢,
我希望你觉得这有帮助:)
归档时间: |
|
查看次数: |
4368 次 |
最近记录: |