Perhaps this may help you:
In XAML:
<DataGrid Name = "DataGrid" MouseRightButtonUp = "DataGrid_MouseRightButtonUp" />
In C # Code:
private void DataGrid_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
DependencyObject dep = (DependencyObject)e.OriginalSource;
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;
string boundPropertyName = FindBoundProperty(columnHeader.Column);
int columnIndex = columnHeader.Column.DisplayIndex;
ClickedItemDisplay.Text = string.Format(
"Header clicked [{0}] = {1}",
columnIndex, boundPropertyName);
}
if (dep is DataGridCell)
{
DataGridCell cell = dep as DataGridCell;
while ((dep != null) && !(dep is DataGridRow))
{
dep = VisualTreeHelper.GetParent(dep);
}
if (dep == null)
return;
DataGridRow row = dep as DataGridRow;
object value = ExtractBoundValue(row, cell);
int columnIndex = cell.Column.DisplayIndex;
int rowIndex = FindRowIndex(row);
ClickedItemDisplay.Text = string.Format(
"Cell clicked [{0}, {1}] = {2}",
rowIndex, columnIndex, value.ToString());
}
}
private int FindRowIndex(DataGridRow row)
{
DataGrid dataGrid = ItemsControl.ItemsControlFromItemContainer(row) as DataGrid;
int index = dataGrid.ItemContainerGenerator.IndexFromContainer(row);
return index;
}
private object ExtractBoundValue(DataGridRow row, DataGridCell cell)
{
string boundPropertyName = FindBoundProperty(cell.Column);
object data = row.Item;
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(data);
PropertyDescriptor property = properties[boundPropertyName];
object value = property.GetValue(data);
return value;
}
private string FindBoundProperty(DataGridColumn col)
{
DataGridBoundColumn boundColumn = col as DataGridBoundColumn;
Binding binding = boundColumn.Binding as Binding;
string boundPropertyName = binding.Path.Path;
return boundPropertyName;
}
}
source
share