2010-10-23 6 views
0

J'ai un TextBoxtxtEditor. Je veux trouver le plus proche des sauts de ligne et sélectionnez-C#/WPF: Comment trouver les sauts de ligne les plus proches de la sélection d'un TextBox

Exemple 1: Avec « aucune sélection »

suppose que la sélection/curseur est *

this is the 1st line of text 
this is *the 2nd line of text 
this is the 3rd line of text 

Je souhaite étendre la sélection telle que la sélection est maintenant

this is the 1st line of text 
*this is the 2nd line of text* 
this is the 3rd line of text 

Exemple 2: Avec Selec tion

this is the 1st line of text 
this is *the 2nd line* of text 
this is the 3rd line of text 

Je souhaite étendre la sélection telle que la sélection est maintenant

this is the 1st line of text 
*this is the 2nd line of text* 
this is the 3rd line of text 

Mise à jour: Solution possible

J'ai trouvé une solution possible, je me demande si quelqu'un a une meilleure 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.NewLine) < 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; 

Répondre

1

Eh bien, la plupart du temps le problème est que votre code est somwhat pléthorique (et donc plus difficile à lire) et beaucoup moins efficace qu'il doit être. La performance ne probablement pas vraiment dans votre cas (ces appels en double à IndexOf et LastIndexOf me frotter dans le mauvais sens), mais personnellement je voudrais réécrire votre code comme ceci:

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; 
Questions connexes