Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Get Mouse Click relative Position

0.00/5 (No votes)
12 Aug 2010 1  
If you need to get the position the mouse was clicked, in relation to a specific UI Element, this might help
Today, I was faced with a requirement where I had to respond to the user clicking on a cell in a manually built grid. Gird your loins - the cell itself was a label in a border in a grid in a stack panel in a grid on the page. Because of the way this particular label was displayed, there was white space to the left of the actual text.

My layout produced some unexpected issues. I tried setting the mouse-up handler for the label, and that didn't work for white space in the cell. The same for the border. Finally, I put the handler in the grid for the entire row, and while the white space problem was solved, the mouse up event was fired for anything in the row that wasn'rt already handled by another handler (buttons).

So in my handler, I do this:

C#
private void FMMetric_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    // make sure the event came from a grid element
    if (sender is Grid)
    {
        // get the grid
        Grid element = sender as Grid;
        // get the first child (if possible). It *should* be a border
        if (element.Children != null && 
            element.Children.Count >= 1 && 
            element.Children[0] is Border)
        {
            Border firstChild = element.Children[0] as Border;
            // now see where the user clicked the mouse in relation to the 
            // discovered border
            Point point = e.GetSafePosition(firstChild);
            // if the X value is <= the actual rendered width of the element, 
            // we can process the mouse click and navigate to the appropriate 
            // page.
            if (point.X <= firstChild.ActualWidth)
            {
                // ... put code here ...
            }
        }
    }
}

Of course the example above is specific to my code, but you should be able to see the technique.

You can use this approach to find the mouse position in relation to any given UI element on the page.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here