我目前设置此方法是为了检测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);
}
我的问题是,我似乎无法获得细胞价值。正如你所看到的,我试图获得行中第一个单元格的值,但它只会崩溃。我有什么想法可以做到这一点? :)
答案 0 :(得分:1)
试试这个。
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;
}
答案 1 :(得分:0)
作为HighCore提到的一个例子:
这里我有一个对象列表(类型为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;