WPF工具包DataGrid中的SelectionChanged获取单元格值
问题描述:
请帮我,我试着从一个SelectionChangedEvent选定行获得Cell [0]的数值。
Please help me, Im trying to get the value of Cell[0] from the selected row in a SelectionChangedEvent.
我只设法获得大量不同Microsoft.Windows.Controls的,我希望IM失去了一些东西愚蠢的。
I am only managing to get lots of different Microsoft.Windows.Controls and am hoping im missing something daft.
希望我可以从这里得到一些帮助...
Hoping I can get some help from here...
private void datagrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Microsoft.Windows.Controls.DataGrid _DataGrid = sender as Microsoft.Windows.Controls.DataGrid;
}
我希望它会是这样的...
I was hoping it would be something like...
_DataGrid.SelectedCells[0].Value;
不过.value的是不是一种选择....
However .Value isn't an option....
很多很多的感谢这已经快把我逼疯了!
丹
Many many thanks this has been driving me mad! Dan
答
请检查如果跌破code会为你工作:
pls, check if code below would work for you:
private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataGrid dataGrid = sender as DataGrid;
if (e.AddedItems!=null && e.AddedItems.Count>0)
{
// find row for the first selected item
DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromItem(e.AddedItems[0]);
if (row != null)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);
// find grid cell object for the cell with index 0
DataGridCell cell = presenter.ItemContainerGenerator.ContainerFromIndex(0) as DataGridCell;
if (cell != null)
{
Console.WriteLine(((TextBlock)cell.Content).Text);
}
}
}
}
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;
}
希望这可以帮助,至于
hope this helps, regards