在代码中动态选择对象

时间:2015-06-24 15:30:27

标签: c# xaml windows-phone

我有一个包含40个矩形(4x10网格)的xaml页面,全部以r1-1到r10-4的格式命名。

我想在代码中迭代这些:

        for (int row = 1; row < 10; row++)
        {
            for (int col = 1; col < 4; col++)
            {
                 ...// what do I need here
            }
        }

请帮忙吗?

3 个答案:

答案 0 :(得分:1)

虽然我不建议这样做,但如果你有参考,你可以简单地遍历Grid Panel中的所有项目。尝试这样的事情:

foreach (UIElement element in YourGrid.Children)
{
    // do something with each element here
}

答案 1 :(得分:0)

您可以按类型或名称找到您的控件:

按类型

public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
            if (child != null && child is T)
            {
                yield return (T)child;
            }

            foreach (T childOfChild in FindVisualChildren<T>(child))
            {
                yield return childOfChild;
            }
        }
    }
}

然后你可以遍历Visual Tree:

foreach (Rectangle r in FindVisualChildren<Rectangle>(window))
{
    // do something with r here
}

按名称

for (int row = 1; row < 10; row++)
{
    for (int col = 1; col < 4; col++)
    {
        var control = this.FindName(string.Format("r{0}-r{1}", row.ToString(), col.ToString()));    
    }
}

答案 2 :(得分:0)

您可以使用以下命令动态获取其名称的元素:

for (int row = 1; row < 10; row++)
{
    for (int col = 1; col < 4; col++)
    {
        var elt = this.FindName("r" + row + "-" + col);
        // do some stuff
    }
}