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?.
private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ProductItem productItem = (ProductItem)dataGrid.SelectedItem; //Datagrid bound with ProductItem
}
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
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());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With