Stu Ayton
Stu Ayton

Reputation: 489

select objects dynamically in code

I have an xaml page with 40 rectangles, (4x10 grid), all named in the format r1-1 through to r10-4.

I would like to iterate through these in code:

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

Any help please?

Upvotes: 0

Views: 52

Answers (3)

PMerlet
PMerlet

Reputation: 2594

You can get dynamically an element by its name using the following :

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

Upvotes: 0

Christian Amado
Christian Amado

Reputation: 943

You can find your control by type or by name:

By type:

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

Then you can iterate through the Visual Tree:

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

By name:

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

Upvotes: 0

Sheridan
Sheridan

Reputation: 69979

Although I wouldn't recommend doing this, you can simply iterate through all of the items in the Grid Panel if you have a reference to it. Try something like this:

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

Upvotes: 1

Related Questions