我在互联网上看到这个主题很常见,我不明白为什么还没有创建一个方法来直接选择datagridview中的单元。在datagridview中选择一个单元并开始编辑
我创建了这个类助手:
using Microsoft.Windows.Controls.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Media;
namespace gestione_magazzino_v4.Classi
{
static class DataGridViewHelper
{
static public DataGridCell GetCell(DataGrid dg, int row, int column)
{
DataGridRow rowContainer = GetRow(dg, row);
if (rowContainer != null)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column); // <<<------ ERROR
if (cell == null)
{
// now try to bring into view and retreive the cell
dg.ScrollIntoView(rowContainer, dg.Columns[column]);
cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
}
return cell;
}
return null;
}
static public DataGridRow GetRow(DataGrid dg, int index)
{
DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index);
if (row == null)
{
// may be virtualized, bring into view and try again
dg.ScrollIntoView(dg.Items[index]);
row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index);
}
return row;
}
static T GetVisualChild<T>(Visual parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild<T>(v);
}
if (child != null)
{
break;
}
}
return child;
}
}
}
我用这个代码:
DataGridCell cell = DataGridViewHelper.GetCell(datagridview, 0, 2);
if (cell != null)
cell.Focus();
但我得到一个错误,我特别强调了,我得到System.NullReferenceException
我不明白缺少什么...网上有很多例子,但它们都与我所做的相同,不明白什么是失踪!
你能与调试器附加检查该'presenter'为空? –
是...'presenter' si null ...是'GetVisualChild'返回值始终为空... – user2263764