0

最初显示我的 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; }
    }
}
4

2 回答 2

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;
    }
}
于 2012-04-28T16:30:30.700 回答
0

回答我自己关于如何设置初始焦点的问题:http: //msdn.microsoft.com/en-us/library/system.windows.input.focusmanager.focusedelement.aspx

于 2012-04-28T16:32:44.083 回答