How to access children in Grid with x/y coordinates instead of index?

本秂侑毒 提交于 2019-12-02 04:20:28

I would make an extension method that takes the desired x-and y-values. There in you go through all children and check if the Grid.GetRow(child) and Grid.GetColumn(child)-methods return the desired values.

As a result I would return an IEnumerable<FrameworkElement> because you can have more than one, one or no elements at this position (not in your example, but for such a method in general).

Something like:

public static class GridExtensions {
    public static IEnumerable<FrameworkElement> GetXYChild(this Grid instance, int x, int y) {
        if (null == instance) {
            throw new ArgumentNullException("instance");
        }
        List<FrameworkElement> list = new List<FrameworkElement>();            
        foreach (FrameworkElement fe in instance.Children) {
            if (Grid.GetRow(fe) == y && Grid.GetColumn(fe) == x) {
                list.Add(fe);
            }
        }
        return list;
    }
}

I have not tested it, make a comment if it does not work. If you only want to return one instance, you can change the code acordingly.

See:

http://www.trillian.com.au/2009/01/how-to-get-element-from-grid-using-xy.html

Snippet:

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()); 
} 

or my partially solution below:

If your coordinates is i = row and j = column then:

CheckBox cbChange = grid.Children[i * x + j - 1] as CheckBox;

where x is how many items a row can contain in your grid. x could be grid.ColumnDifinitions.Count. This, however, will only work if you your grid is uniform.

(I have not worked so much with WPF so I don't know whether there is a more intuitive way)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!