Wednesday, December 23, 2009

Right Click to select the Datagrid in WPF

First, find the index for the datagrid by mouse position
[sourcecode language="csharp"]
int _OldIndex = this.GetCurrentIndex(e.GetPosition, datagrid);
if (_OldIndex < 0)
return;
datagrid.SelectedIndex = _OldIndex;
[/sourcecode]
Function to find the index using mouseposition
[sourcecode language="csharp"]
private int GetCurrentIndex(GetPositionDelegate getPosition, DataGrid datagrid)
{
int _Index = -1;
for (int _RowCount = 0; _RowCount < datagrid.Items.Count; ++_RowCount)
{
DataGridRow _Item = GetListViewItem(_RowCount, datagrid);
if (this.IsMouseOverTarget(_Item, getPosition))
{
_Index = _RowCount;
break;
}
}
return _Index;
}
[/sourcecode]

To get the item for the given index value
[sourcecode language="csharp"]
private DataGridRow GetListViewItem(int index, DataGrid datagrid)
{
if (datagrid.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated)
return null;
return datagrid.ItemContainerGenerator.ContainerFromIndex(index) as DataGridRow;
}
[/sourcecode]