C#/WPF: How to find the closest line breaks from the selection of a TextBox
I have a TextBox
txtEditor
. I want to find the nearest line breaks and select it
Example 1: With "no selection"
suppose the selection/cursor is *
this is the 1st line of text
this is *the 2nd line of text
this is the 3rd line of text
I want to extend the selection such that the selection is now
this is the 1st line of text
*this is the 2nd line of text*
this is the 3rd line of text
Example 2: With selection
this is the 1st line of text
this is *the 2nd line* of text
this is the 3rd line of text
I want to extend the selection such that the selection is now
this is the 1st line of text
*this is the 2nd line of text*
this is the 3rd line of text
Update: Possible solution
I found a possible solution, wonder if anyone got a better solution?
string tmp = txtEditor.Text;
int selStart = txtEditor.SelectionStart;
int selLength = txtEditor.SelectionLength;
int newSelStart;
int newSelLength;
string tmp1 = tmp.Substring(0, selStart);
if (tmp1.LastIndexOf(Environment.N开发者_如何学GoewLine) < 0)
{
newSelStart = 0;
}
else
{
newSelStart = tmp1.LastIndexOf(Environment.NewLine) + Environment.NewLine.Length;
}
tmp1 = tmp.Substring(selStart);
if (tmp1.IndexOf(Environment.NewLine) < 0)
{
newSelLength = tmp.Length;
}
else
{
newSelLength = tmp1.IndexOf(Environment.NewLine) + selStart - newSelStart;
}
txtEditor.SelectionStart = newSelStart;
txtEditor.SelectionLength = newSelLength;
Well, mostly the problem is that your code is somwhat bloated (and thus harder to read) and a lot less efficient than it needs to be. Performance probably doesn't really matter in your case (those duplicate calls to IndexOf
and LastIndexOf
rub me the wrong way), but personally I'd rewrite your code like this:
string tmp = txtEditor.Text;
int selStart = txtEditor.SelectionStart;
int selLength = txtEditor.SelectionLength;
int newSelStart = tmp.LastIndexOf(Environment.NewLine, selStart);
if (newSelStart == -1)
newSelStart = 0;
int newSelEnd = tmp.IndexOf(Environment.NewLine, selStart);
if (newSelEnd == -1)
newSelEnd = tmp.Length;
txtEditor.SelectionStart = newSelStart;
txtEditor.SelectionLength = newSelEnd - newSelStart;
精彩评论