C# 在WPF中获取DataGrid中单元格的值
对于WinForms,它是:C# 在WPF中获取DataGrid中单元格的值,c#,wpf,datagrid,C#,Wpf,Datagrid,对于WinForms,它是: var value = DataGridView.Rows[0].Cells[0].Value 有什么方法可以在WPF中获取它吗?我认为最好的方法是使用Items属性并直接访问您的数据项: var dataItem = dataGrid.Items[0] as ...; 但是您可以使用这个类来获取单元格并使用GetValue()方法访问值(更像您的示例) 代码取自此处: 静态类DataGridHelper{ 静态公共DataGridCell GetCell(Da
var value = DataGridView.Rows[0].Cells[0].Value
有什么方法可以在WPF中获取它吗?我认为最好的方法是使用Items属性并直接访问您的数据项:
var dataItem = dataGrid.Items[0] as ...;
但是您可以使用这个类来获取单元格并使用GetValue()方法访问值(更像您的示例)
代码取自此处:
静态类DataGridHelper{
静态公共DataGridCell GetCell(DataGrid dg,int行,int列){
DataGridRow rowContainer=GetRow(dg,row);
if(rowContainer!=null){
DataGridCellsPresenter=GetVisualChild(行容器);
//尝试获取该单元,但它可能已虚拟化
DataGridCell=(DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(列);
if(单元格==null){
//现在试着把手机放在视野里,然后拿回手机
dg.ScrollIntoView(行容器,dg.Columns[列]);
单元格=(DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(列);
}
返回单元;
}
返回null;
}
静态公共DataGridRow GetRow(DataGrid dg,int索引){
DataGridRow行=(DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(索引);
if(行==null){
//可能已虚拟化,请查看并重试
总卷轴视图(总项目[索引]);
行=(DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(索引);
}
返回行;
}
静态T GetVisualChild(可视父级),其中T:Visual{
T child=默认值(T);
int numVisuals=VisualTreeHelper.GetChildrenCount(父级);
对于(int i=0;i
通常,您不需要这样做。在WPF中,datagrid用于数据绑定,这意味着存在一个与单元格具有相同值的基础集合或对象,因此您需要直接访问该集合/对象。如果您需要访问单元格值,您可能需要重新考虑您的设计。正如我告诉每一位winforms开发人员的那样,我发现他对WPF有异议。。。忘了从winforms中学到的一切吧,这是一个不同的(比IMO更好)框架,需要完全不同的思维方式。看看MVVM,熟悉WPF绑定功能
static class DataGridHelper {
static public DataGridCell GetCell(DataGrid dg, int row, int column) {
DataGridRow rowContainer = GetRow(dg, row);
if (rowContainer != null) {
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
// try to get the cell but it may possibly be virtualized
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
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;
}
}