Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
XamDataGrid - Setting keyboard focus back to Add row
//Add a PreviewKeyDown event handler to the data grid and call the HandleFocus method.
private void DataGrid_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
XamDataGridFocusHelper.HandleFocus(sender, e);
}
using System;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using Infragistics.Windows.DataPresenter;
namespace Chris.Blog
{
public static class XamDataGridFocusHelper
{
public static void HandleFocus(XamDataGrid grid, Key keyPressed)
{
if ((keyPressed == Key.Tab && !Keyboard.IsKeyDown(Key.LeftShift) && !Keyboard.IsKeyDown(Key.RightShift) && IsLastFieldFocused(grid)))
{
grid.Dispatcher.BeginInvoke(new Action(() =>
CellValuePresenter.FromCell(grid.RecordManager.CurrentAddRecord.Cells.First(c => c.Field.AllowEditResolved)).Editor.StartEditMode()),
DispatcherPriority.Background, null);
}
}
public static void HandleFocus(object grid, System.Windows.Input.KeyEventArgs e)
{
HandleFocus((XamDataGrid)grid, e.Key);
}
private static bool IsLastFieldFocused(XamDataGrid grid)
{
var addRecord = GetAddRecord(grid);
if (addRecord == null)
return false;
return grid.ActiveCell.Field.ActualPosition.Column ==
addRecord.FieldLayout.Fields.Where(f => f.Visibility == Visibility.Visible)
.Max(f => f.ActualPosition.Column);
}
private static DataRecord GetAddRecord(XamDataGrid grid)
{
foreach (DataRecord item in grid.RecordManager.DataPresenter.Records)
{
if (item.IsAddRecord)
return item;
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment