0

I am having problem with DataGrid navigation using arrow keys when my DataGrid is displayed initially. Up/down keys do not change the current row. Only after I click on a row do the keys start working. Has something to do with the focus, but I do not know how to set focus programmatically.

<DataGrid ItemsSource="{Binding Tasks}"
              AutoGenerateColumns="False"
              SelectedItem="{Binding SelectedTask, Mode=TwoWay}"
              SelectionMode="Single">
      <DataGrid.Columns>
        <DataGridTextColumn Header="Title"
                            Binding="{Binding Title}" />
      </DataGrid.Columns>
</DataGrid>

class MainViewModel : ModelBase
{
    private readonly ObservableCollection<TaskModel> tasks = new ObservableCollection<TaskModel>();
    public MainViewModel()
        : base()
    {
        this.Tasks.Add(new TaskModel("task0"));
        this.Tasks.Add(new TaskModel("task1"));
        this.Tasks.Add(new TaskModel("task2"));
        this.SelectedTask = this.Tasks[0];
    }<br>
    public TaskModel SelectedTask { get; set; }
    public ObservableCollection<TaskModel> Tasks
    {
        get { return this.tasks; }
    }
}
H.B.
  • 166,899
  • 29
  • 327
  • 400
akonsu
  • 28,824
  • 33
  • 119
  • 194

2 Answers2

0

You could also do this:

<DataGrid PreviewKeyDown="DataGrid_PreviewKeyDown"

.

private void DataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
{
    DataGrid grid = sender as DataGrid;
    ICollectionView view = CollectionViewSource.GetDefaultView(grid.ItemsSource);

    switch (e.Key)
    {
        case Key.Up:
            view.MoveCurrentToPrevious();
            e.Handled = true;
            break;
        case Key.Down:
            view.MoveCurrentToNext();
            e.Handled = true;
            break;
    }
}
LPL
  • 16,827
  • 6
  • 51
  • 95
  • I've the same problem, but this solution didn't work unfortunately. The event isn't executed in a databound sorted datagrid... – Herman Cordes Oct 11 '12 at 10:20
0

to answer my own question about how to set the initial focus: http://msdn.microsoft.com/en-us/library/system.windows.input.focusmanager.focusedelement.aspx

akonsu
  • 28,824
  • 33
  • 119
  • 194