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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With