Datagrid 行选择事件,WPF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22492295/
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
Datagrid row selection event, WPF
提问by RobinAtTech
I did a simple data binding to a datagrid. Now I would like to get the relevant rowdata (entire row data) when the row is clicked in the datagrid. Do I need to use the mouseclickevent since there are no row selection events?.
我做了一个简单的数据绑定到数据网格。现在我想在数据网格中单击行时获取相关的行数据(整行数据)。由于没有行选择事件,我是否需要使用 mouseclickevent?。
回答by RobinAtTech
private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ProductItem productItem = (ProductItem)dataGrid.SelectedItem; //Datagrid bound with ProductItem
}
回答by Jim
I have done it this way. Others may have a simpler way ! Mine deals with an Observable Collection of a PlayListEntries class for a mediaplayer. Hope this can help
我已经这样做了。其他人可能有更简单的方法!我的处理媒体播放器的 PlayListEntries 类的 Observable 集合。希望这可以帮助
private void PlayList_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
DependencyObject dep = (DependencyObject)e.OriginalSource;
// iteratively traverse the visual tree
while ((dep != null) && !(dep is DataGridCell) && !(dep is DataGridColumnHeader))
{
dep = VisualTreeHelper.GetParent(dep);
}
if (dep == null)
return;
if (dep is DataGridColumnHeader)
{
DataGridColumnHeader columnHeader = dep as DataGridColumnHeader;
// do something
}
if (dep is DataGridCell)
{
DataGridCell cell = dep as DataGridCell;
// navigate further up the tree
while ((dep != null) && !(dep is DataGridRow))
{
dep = VisualTreeHelper.GetParent(dep);
}
DataGridRow row = dep as DataGridRow;
var ple = (PlayListEntry)row.Item;
// From here you have access to all of the row.
// Each column is suitable bound.
// I can post the xaml if you are not sure.
//object value = ExtractBoundValue(row, cell); //4
//int columnIndex = cell.Column.DisplayIndex;
//int rowIndex = FindRowIndex(row);
//var s = string.Format("Cell clicked [{0}, {1}] = {2}",rowIndex, columnIndex, value.ToString());
}
}

