2012-04-28 44 views
0

我最初顯示DataGrid時遇到使用箭頭鍵的DataGrid導航問題。上/下鍵不會改變當前行。只有當我點擊一行後,鍵纔開始工作。與焦點有關,但我不知道如何以編程方式設置焦點。鍵不能與綁定DataGrid上的SelectedItem一起使用

<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; } 
    } 
} 

回答

0

你也可以這樣做:

<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; 
    } 
} 
+0

我有同樣的問題,但這種解決方案並不遺憾的是工作。事件不會在數據綁定的數據網格中執行... – 2012-10-11 10:20:16

相關問題