Friday, September 12, 2008

Silverlight Tip 6#: How to start editing cell of DataGrid by pressing text key

When you press text key (f.e 'a') on selected cell of MS Excel sheet, you automatically start write to the cell. Why don't implement this behavior with Silverlight DataGrid control? I have written some code to implement it:

void dataGrid_KeyDown(object sender, KeyEventArgs e)
{
//editing: bool flag which you set in BeginEdit, CancelEdit, CommitEdit event handlers
if (!editing)
{
//IsTextKey: custom function to check if pressed key is a text key (f.e letter, digit)
if (IsTextKey(e))
{
dataGrid.BeginEdit(e);
}
}
}


void dataGrid_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e)
{
if (e.Column.DisplayIndex == 0)
{
TextBox t = e.EditingElement as TextBox;

t.Focus();

KeyEventArgs args = e.EditingEventArgs as KeyEventArgs;

if (args != null)
{
if (IsTextKey(args))
{
//GetStrFromKey: custom function to get char from pressed key
//There isn't KeyPress event and KeyChar property of KeyPressEventArgs
t.Text = GetStrFromKey(args);
t.Select(t.Text.Length, t.Text.Length);
}
}
}
}

No comments: