Fixus
Fixus

Reputation: 4641

How to get dynamically added UI element from C#

I have a problem with getting to properties of dynamically added field.

If I do something like that

<Rectangle Name="field_0_0" Width="10" Height="10" />

then in C# code I can get to this by

field_0_0.Width = 20;

But in my app I've done something like this

for(i = 0; i < 5; i++) {
    for(j = 0; j < 5; j++) {
        String fieldName = "field_" + i + "_" + j;
        Rectangle rec = new Rectangle();
        rec.Name = fieldName;
        Container.Children.Add(rec);
    }
 }

Now the problem is that I don't know how to call these fields in my code when I have them on screen? For example I want to change fill color of field_1_1

How can I get this rectangle from name ?

Upvotes: 1

Views: 638

Answers (1)

keyboardP
keyboardP

Reputation: 69362

You can use the FindName method.

object findRect = Container.FindName("field_1_1");
if (findRect is Rectangle)
{        
    Rectangle rect = findRect as Rectangle;
    //change rect properties
}

Upvotes: 2

Related Questions