How to select a row or a cell in WPF DataGrid programmatically?

后端 未结 4 1335
臣服心动
臣服心动 2021-01-11 16:55

In WinForm DataGridView, it automatically selects the first row when initialized. It drove me crazy when I tried to turn that feature off. Moving to WPF DataGrid, it seems M

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-11 17:50

    You can do this consistently in the DataGrid.Loaded event. Just obtain the first row and have the row fire the selection event.

    void MyGridLoaded(...) {
    DataGridRow r = yourGrid.ItemContainergenerator.ContainerFromIndex(0) as DataGridRow;
      if(r != null) {
         r.IsSelected = false;
         r.IsSelected = true;
      }
    
    } 
    

    I'm not sure this is a bug because you may not be guaranteed to have selection events fire from your object until the control is loaded. Don't know.

提交回复
热议问题