在我的 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 应用程序不支持这些命名空间。
最佳答案
你可以这样做
for (int i = 1; i <=20; i++)
{
Button ele = (Button) MainGrid.FindName("btn"+i);
}
这里 MainGrid 是具有按钮控件的 Grid 元素的名称
关于c# - 将字符串转换为控件名称 c# wp8.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36327325/