Thursday, September 11, 2008

Silverlight Tip 5#: DataGrid PreparingCellForEdit event

Recently I've used DataGridTemplateColumn in DataGrid control and I've implemented selecting text in cell before editing. This is standard behavior of predefined DataGridTextColumn, but using DataGridTemplateColumn you must implement it yourself (sample code below).

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

int length = t.Text.Length;

t.Focus();

KeyEventArgs args = e.EditingEventArgs as KeyEventArgs;

if (args != null)
{
if (args.Key == Key.F2)
t.Select(length, length);
}
else
{
t.Select(0, length);
}
}
}

No comments: