Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing tab in Silverlight TextBox

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.

like image 271
Eric Schoonover Avatar asked Apr 02 '09 03:04

Eric Schoonover


2 Answers

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.

like image 95
joshcomley Avatar answered Nov 11 '22 04:11

joshcomley


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

like image 34
Johannes Avatar answered Nov 11 '22 06:11

Johannes