Friday, November 21, 2008

Silverlight 2.0 and Textbox control that understands TAB key

So we are writing a small application in Silverlight 2.0 and wanted a textbox where if the user presses the TAB key, the cursor stays in the same box with a "Tab" ["\t"] inserted at the place of the cursor and the curs. Unfortunately like any other web platform, here also "Tab" has become more like a navigation mechanism which you use to navigate from one control to another.

So here is what we did. First we wrote our custom component which extends a regular TextBox. By default we set it's "AcceptsReturn" field true. Then we wrote a simple function named "HandleTab()" which will insert a Tab ("\t") character at the place of the cursor.

After you are done there, now what is remaining is to capture the "Tab" key press event. This needs to be on the container and not on the control itself. Unfortunately onKeyUp event does not capture the Tab key so we need to do it in onKeyDown event handler. Obviously we would want to capture this event for just our text box & that too on the "TAB" key, we will do the following:
============================================
void tb_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key.Equals(Key.Tab))
{
if (e.OriginalSource.GetType().Equals(typeof(CodeTextBox)))
{
(e.OriginalSource as CodeTextBox).HandleTab();
e.Handled = true;//prevent further propagation
}
}
}
=======================================================
and here is the code for HandleTab() function
----------------------------------------------
public class CodeTextBox : TextBox
{

public CodeTextBox()
{
this.AcceptsReturn = true;
}

public void HandleTab()
{
string tbText = this.Text;
int cursorPosition = this.SelectionStart;
int contentLength = tbText.Length; if (cursorPosition >= contentLength)
{
this.Text = tbText + "\t";
}
else
{
string leftSideContent = tbText.Substring(0, cursorPosition);
string rightSideContent = tbText.Substring(cursorPosition);
this.Text = leftSideContent + "\t" + rightSideContent;
}
this.SelectionStart = cursorPosition + 1;
}


}
============================================
This is pretty basic stuff but I think it can get the job done. Shift+Tab is yet to be implemented.

Also I don't know why but when you [Tab] does not insert 8 characters like you would normally expect. However when you copy the tabbed code from this textbox to your notepad or any other windows application, you see text as you would normally see. Any ideas?

Any comments??

Enjoy!!!