将字符串转换为控件名称 c# wp8.1

Convert string to Control name c# wp8.1

在我的MainPage.xaml中,有20个按钮控件,分别命名为btn1、btn2、btn3、……btn20。现在我需要在后面的代码中使用这个按钮。

我打算使用 for 循环并为每个按钮编写代码。但我的问题是我无法将字符串转换为按钮名称。

例如,

for (int i = 1; i <=20; i++)
{
     string button = "btn" + i;

     // Convert string to button somehow
     // Do something with button
}

我在 Google 上搜索过,那里有很多关于从字符串转换控件名称的文章。但它们适用于 Windows 表格。 Windows phone 应用程序不支持这些命名空间。

您不能将字符串转换为按钮实例但您需要btnN (f.e.btn1)class 字段值使用 反射:

Button button = (Button)GetType().GetField($"btn{i}", BindingFlags.Instance).GetValue(this);

或者更有效的方法:使用字典查找按钮:

// Place this in your form constructor
Dictionary<string, Button> buttons = new Dictionary<string, Button>
{
    { "btn1", btn1 },
    { "btnN", btn2 }
};

// and later where you want to get your buttons by their name...
Button btn1 = buttons[$"btn{i}"];

你可以这样做

for (int i = 1; i <=20; i++)
{
       Button ele =  (Button) MainGrid.FindName("btn"+i);
}

这里MainGrid是有按钮控件的Grid元素的名字

终于找到解决方法

    for (int i = 1; i <= 20; i++) 
        {
            var ele = GridMain.FindName("btn" + i);

            // @Archana you missed this line
            Button button = ele as Button;

            // Do what you want to do with your control 
            button.Background = background;
            button.Foreground = foreground;                
        }