wpf datagrid以编程方式选择第一个单元格

时间:2014-06-08 23:14:11

标签: wpf datagrid focus

我的datagrid SelectionMode =“Single”,每当我单击Description列或任何其他列中的单元格时,我都需要将单元格焦点切换到第一个单元格。

这是我尝试的代码

private void dgvConfig_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        DependencyObject dep = (DependencyObject)e.OriginalSource;
        // iteratively traverse the visual tree
        while ((dep != null) &&
                !(dep is DataGridCell) &&
                !(dep is DataGridColumnHeader))
        {
            dep = VisualTreeHelper.GetParent(dep);
        }

        if (dep == null)
            return;

        if (dep is DataGridColumnHeader)
        {
            string columnHead = "";
            DataGridColumnHeader columnHeader = dep as DataGridColumnHeader;
            columnHead = columnHeader.Column.Header.ToString();
            LoadGridview(columnHead);
            //MessageBox.Show(columnHeader.Column.DisplayIndex.ToString());
        }

        if (dep is DataGridCell)
        {
            DataGridCell cell = dep as DataGridCell;
            string cellName = cell.Column.Header.ToString();

            if (cellName.Equals("Description"))
            {


                cell.Focus();
                string datagridselect;
                //datagridselect = DataGrid.SelectedIndexProperty[]
                //var cellInfo = dgvConfig.SelectedCells[0];
                //var xt = dgvConfig.CurrentCell.Column.

                // the prob is I cant seem to access an array to move the focus to the first column of that selected row


            }

        }


    }

1 个答案:

答案 0 :(得分:1)

试一试:

 private void dgShow_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
    {
        foreach(DataGridCellInfo info in dgShow.SelectedCells)
        {
           if( info.Column.Header.ToString()=="Name")
           {
               dgShow.CurrentCell = info;
               break;
           }
        }
    }