Advertisement
rufwork

Handling tab presses in UWP TextBoxes

Feb 3rd, 2016
354
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.21 KB | None | 0 0
  1. // Replace default "tab means tab to next control" action.
  2. // Note: This isn't even an alpha; I'm fiddling with this problem now.
  3. case VirtualKey.Tab:
  4.     if (Window.Current.CoreWindow.GetKeyState(VirtualKey.Shift).HasFlag(CoreVirtualKeyStates.Down))
  5.     {
  6.         StringBuilder builder = new StringBuilder();
  7.         string[] astrLines = this.SelectedText.Split(this.SelectionLineEnding); // I'm doing lots of xplat stuff. SelectionLineEnding in a UWP TextBox is \r
  8.         string toAppend = string.Empty;
  9.  
  10.         if (astrLines.Length > 0 && astrLines[astrLines.Length - 1].EndsWith(this.SelectionLineEnding))
  11.         {
  12.             astrLines[astrLines.Length - 1] = astrLines[astrLines.Length - 1].RemoveLastNewLine(true); // In this case, blasts last \r if it exists
  13.             toAppend = this.SelectionLineEnding;
  14.         }
  15.  
  16.         foreach (string line in astrLines)
  17.         {
  18.             // See below for _deleteATab...
  19.             builder.Append(_deleteATabWorthOfLeadingSpaces(line) + this.SelectionLineEnding);
  20.         }
  21.  
  22.         this.SelectedText = builder.ToString().RemoveLastNewLine(true) + toAppend;
  23.     }
  24.     else
  25.     {
  26.         // MdTextBox is an extension of TextBox, and Tab is just a string of spaces that's whatever the user says Tab should be (default "    ")
  27.         this.SelectedText = MdTextBox.Tab + this.SelectedText.Replace(this.SelectionLineEnding, this.SelectionLineEnding + MdTextBox.Tab);
  28.         if (this.SelectedText.EndsWith(this.SelectionLineEnding))
  29.         {
  30.             this.SelectedText = this.SelectedText.DeleteLastNChars(MdTextBox.Tab.Length);   // Does what it seems to; Removes X characters from the end of the string.
  31.         }
  32.     }
  33.  
  34.     e.Handled = true;
  35.     break;
  36.  
  37. // ...
  38.  
  39. private string _deleteATabWorthOfLeadingSpaces(string value)
  40. {
  41.     string ret = value;
  42.     int intTabSize = MdTextBox.Tab.Length;
  43.     Tuple<string, string> tupe = value.PullLeadingAndTrailingSpaces(); // Tuple will have Item1 with spaces at front & Item2 with spaces at end
  44.  
  45.     if (tupe.Item1.Length >= intTabSize)
  46.     {
  47.         ret = value.Substring(intTabSize);
  48.     }
  49.     else if (tupe.Item1.Length > 0)
  50.     {
  51.         ret = value.Substring(tupe.Item1.Length);
  52.     }
  53.  
  54.     return ret;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement