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

后端 未结 4 1324
臣服心动
臣服心动 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:31

    I'm glad to report I found a solution for this problem through ItemContainerGenerator.StatusChanged event.

    dataGrid.ItemContainerGenerator.StatusChanged += new EventHandler(ItemContainerGenerator_StatusChanged);
    
    void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
            {
                if (dataGrid.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
                {
                    dataGrid.SelectedIndex = 0;
                }
            }
    

    It looks when this event is fired with status ContainersGenerated, dataGrid is fully initialized. To me, this is more like DataGridView's DataBindingComplete event in WinForm. If so, the "DataContextChanged" event should really be called "DataContextChanging" event.

    This was inspired by a post here I accidently found while looking for another clue.

提交回复
热议问题