简体   繁体   中英

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 ?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM