WPF Datagrid set selected row

后端 未结 8 1369
无人共我
无人共我 2020-11-27 05:08

How do I use the Datagrid.SelectedItem to select a row programmatically?

Do I first have to create a IEnumerable of DataGridRow

8条回答
  •  鱼传尺愫
    2020-11-27 05:28

    please check if code below would work for you; it iterates through cells of the datagris's first column and checks if cell content equals to the textbox.text value and selects the row.

    for (int i = 0; i < dataGrid.Items.Count; i++)
    {
        DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(i);
        TextBlock cellContent = dataGrid.Columns[0].GetCellContent(row) as TextBlock;
        if (cellContent != null && cellContent.Text.Equals(textBox1.Text))
        {
            object item = dataGrid.Items[i];
            dataGrid.SelectedItem = item;
            dataGrid.ScrollIntoView(item);
            row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
            break;
        }
    }
    

    hope this helps, regards

提交回复
热议问题