wpf 如何获取 DataGridRow 单元格值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28533905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get DataGridRow cell value?
提问by Kim Regine Lim
I currently have this method set up to detect double clicks on each row in my DataGrid:
我目前设置了此方法来检测 DataGrid 中每一行的双击:
private void Row_DoubleClick(object sender, RoutedEventArgs e)
{
DataGridRow row = (DataGridRow)sender;
DataRow dr = (DataRow)row.DataContext;
string value = dr[0].ToString();
MessageBox.Show(value);
}
My problem though is I can't seem to get cell values. As you can see I tried to get the value of the first cell in the row but it would just crash. Any ideas how I can do this? :)
我的问题是我似乎无法获得单元格值。如您所见,我尝试获取行中第一个单元格的值,但它会崩溃。任何想法我怎么能做到这一点?:)
回答by Peter O?bot
Try this.
尝试这个。
public static DataGridCell GetCell(DataGrid dataGrid, int row, int column)
{
DataGridRow rowContainer = GetRow(dataGrid, 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
dataGrid.ScrollIntoView(rowContainer, dataGrid.Columns[column]);
cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
}
return cell;
}
return null;
}
回答by Derek
As an example of what HighCore mentioned:
作为 HighCore 提到的一个例子:
Here I have a list of objects ( with type EntitySet ), and I set that as the ItemsSource for the dataGrid. Then in the double-click I just cast the SelectedItem as an EntitySet.
在这里,我有一个对象列表(类型为 EntitySet ),并将其设置为 dataGrid 的 ItemsSource。然后在双击中我只是将 SelectedItem 转换为 EntitySet。
public List<EntitySet> EntitySets { get; set; }
public EntitySetsForm( List<EntitySet> entitySets )
{
InitializeComponent();
EntitySets = entitySets;
dataGrid.ItemsSource = entitySets;
}
private void dataGrid_MouseDoubleClick( object sender, MouseButtonEventArgs e )
{
EntitySet entitySet = dataGrid.SelectedItem as EntitySet;
if ( entitySet == null ) return;

