我做了一个简单的数据绑定到数据网格。现在,我希望在datagrid中单击行时获取相关的rowdata(整行数据)。我是否需要使用mouseclickevent,因为没有行选择事件?
答案 0 :(得分:4)
private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ProductItem productItem = (ProductItem)dataGrid.SelectedItem; //Datagrid bound with ProductItem
}
答案 1 :(得分:1)
我这样做了。其他人可能会有更简单的方法!我处理媒体播放器的PlayListEntries类的Observable Collection。希望这可以帮助
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());
}
}