键不适用于DataGrid上的绑定SelectedItem

时间:2012-04-28 15:59:30

标签: wpf mvvm wpfdatagrid

我最初显示DataGrid时,使用箭头键导致DataGrid导航出现问题。向上/向下键不会更改当前行。只有在我点击一行后,才能开始工作。与焦点有关,但我不知道如何以编程方式设置焦点。

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

2 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分:0)