Tuesday, January 13, 2009

How to get an element from a grid using x,y coordinates

Occasionaly you might come up against the requirement to get a list of UIElements that occupy a specific row and column within a Grid control. This might occur when the rows and columns are not only used for layout, but also map to some real world data. The example that comes to mind is a calendar control where the columns represent dates and the rows are time spans within the day.

Although it's easy to assign UIElements to rows and columns using the Grid.SetRow/Column attached property setters, there is no API that allows you to ask the grid what elements exist at a given location.

This extension method uses a simple linq expression to find any child elements of the grid that occupy the specified row and column.
public static Collection<TElement> GetElements<TElement>(this Grid grid, int row, int column) 
where TElement : UIElement
{
var elements = from UIElement element in grid.Children
where element is TElement &&
Grid.GetRow(element) == row &&
Grid.GetColumn(element) == column
select element as TElement;
return new Collection<TElement>(elements.ToList());
}

4 comments:

  1. Wow, thanks. This helped alot. I was simply using a for each loop before but this is a better option.

    ReplyDelete
  2. Very nice, ill be using this a fair bit I imagine...

    ReplyDelete
  3. Wonderfull. I was going mad trying to find this in WPF, but it's simply not built in ...

    ReplyDelete
  4. Thanks for the post it helped me get to where I wanted.

    I have a table with a check box column that I wanted to check all and uncheck all according to top check box value.

    Your post helped me get to the right row/column for the check box elements.

    (I have posted a link to your blog from my post here)

    ReplyDelete

Note: Only a member of this blog may post a comment.