views:

1456

answers:

3

How can I capture a tab entered in a Silverlight TextBox and render 4 spaces (or a tab) in it's place?

I can't figure out how to block the tab navigation.

+1  A: 

I am not sure how to solve your problem, I hacked together a solution though that seems to work.

Set the KeyDown event as below.

expenses.KeyDown += new KeyEventHandler(expenses_KeyDown);

In that event I put the following code:

void expenses_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Tab)
            {
                expenses.Text += "    ";
                expenses.Focus();
                expenses.LostFocus += new RoutedEventHandler(expenses_LostFocus);
            }
        }

And then in LostFocus:

void expenses_LostFocus(object sender, RoutedEventArgs e)
        {
            expenses.Focus();
            expenses.Select(expenses.Text.Length - 1, 0);
        }

The last line in LostFocus sets the editing cursor to the end of the text, otherwise, when it gets focus, the cursor position is in the beginning of the textbox

Johannes
+2  A: 

Here is what I do (similar to Johannes' code):

     private const string Tab = "    ";
 void textBox_KeyDown(object sender, KeyEventArgs e)
 {
  if (e.Key == Key.Tab)
  {
   int selectionStart = textBox.SelectionStart;
   textBox.Text = String.Format("{0}{1}{2}", 
    textBox.Text.Substring(0, textBox.SelectionStart),
    Tab,
    textBox.Text.Substring(textBox.SelectionStart + textBox.SelectionLength, (textBox.Text.Length) - (textBox.SelectionStart + textBox.SelectionLength))
    );
   e.Handled = true;
   textBox.SelectionStart = selectionStart + Tab.Length;
  }
 }

This behaves just how you expect even if you select some text and hit the ol' "Tab" key.

One more thing: I tried having the tab string as "\t", but to no avail. The tab rendered, but was the width of a single space - hence the value for the Tab const being four spaces.

joshcomley
+1  A: 

This seemed to work well for me, and does not require the second event handler or hard coding of the text box name:

void TabbableTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Tab)
            {
                e.Handled = true;

                var tb = ((TextBox)sender);
                tb.Text += "\t";
                tb.Select(tb.Text.Length, 0);
            }
        }
Brad Joss