select 在代码中动态对象

select objects dynamically in code

我有一个包含 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
            }
        }

有什么帮助吗?

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

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

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

按类型:

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

然后您可以遍历可视化树:

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

您可以使用以下方法按名称动态获取元素:

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