Jac*_*ack 5 .net c# wpf richtextbox
我正在寻找排序RichTextBox行的最佳方法,我现在正在使用它:
public void SortLines(object sender, EventArgs e)
{
TextPointer pStart = TextInput.Document.ContentStart;
TextPointer pEnd = TextInput.Document.ContentEnd;
TextRange text = new TextRange(pStart, pEnd);
string[] lines = text.Text.Split('\n');
Array.Sort(lines);
text.Text = String.Join(String.Empty, lines);
}
Run Code Online (Sandbox Code Playgroud)
有最佳方法吗?
当我调用它时,光标放在第一个RichTextBox行中,我该如何将它放在以前的位置?我尝试设置pStart/pEnd和CaretPositiom,但属性是只读的.
我希望这很清楚.提前致谢.
就排序而言,此解决方案与您建议的解决方案没有什么不同,但我发现它更优雅+它处理光标位置和选择:
public void SortLines(object sender, EventArgs e)
{
rtb.HideSelection = false; //for showing selection
/*Saving current selection*/
string selectedText = rtb.SelectedText;
/*Saving curr line*/
int firstCharInLineIndex = rtb.GetFirstCharIndexOfCurrentLine();
int currLineIndex = rtb.Text.Substring(0, firstCharInLineIndex).Count(c => c == '\n');
string currLine = rtb.Lines[currLineIndex];
int offset = rtb.SelectionStart -firstCharInLineIndex;
/*Sorting*/
string[] lines = rtb.Lines;
Array.Sort(lines, delegate(string str1, string str2) { return str1.CompareTo(str2); });
rtb.Lines = lines;
if (!String.IsNullOrEmpty((selectedText)))
{
/*restoring selection*/
int newIndex = rtb.Text.IndexOf(selectedText);
rtb.Select(newIndex, selectedText.Length);
}
else
{ /*Restoring the cursor*/
//location of the current line
int lineIdx = Array.IndexOf(rtb.Lines, currLine);
int textIndex = rtb.Text.IndexOf(currLine);
int fullIndex = textIndex + offset;
rtb.SelectionStart = fullIndex;
rtb.SelectionLength = 0;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1772 次 |
| 最近记录: |