简体   繁体   English

如何从C#中动态添加UI元素

[英]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 然后在C#代码中,我可以通过

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 例如,我想更改field_1_1填充颜​​色

How can I get this rectangle from name ? 如何从名称中获取此矩形?

You can use the FindName method. 您可以使用FindName方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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