WPF - Get Grid's row and column indices by mouse position

 I'm trying to find out what are the row index and column index of a grid by given mouse position.

 

Every search I tried ot me these options:


int rowIndex = Grid.GetRow(myButton);

or

private void OnMouseMove(object sender, MouseEventArgs e)
{
    var element = (UIElement)e.Source;

    int c = Grid.GetColumn(element);
    int r = Grid.GetRow(element);
}

 

Which are nice, but what if I don't have any elements in grid?

 

Here comes my solution, its based on Grid's ColumnDefinition and RowDefinition:

 

public static void GetRowColumn(this Grid @this, Point position, out int row, out int column)
{
    column = -1;
    double total = 0;
    foreach (ColumnDefinition clm in @this.ColumnDefinitions)
    {
        if (position.X < total)
        {
            break;
        }
        column++;
        total += clm.ActualWidth;
    }
    row = -1;
    total = 0;
    foreach (RowDefinition rowDef in @this.RowDefinitions)
    {
        if (position.Y < total)
        {
            break;
        }
        row++;
        total += rowDef.ActualHeight;
    }
}

 

Hope it helps all you guys like me.

Ofir

 

Thank you for your interest!

We will contact you as soon as possible.

Send us a message

Oops, something went wrong
Please try again or contact us by email at info@tikalk.com