for (int r = 0; r < m; r++)
{
TextBlock myTextBlockr = new TextBlock() { Text = "Text Block", Width = 350, Height = 40, FontSize = 20, VerticalAlignment = VerticalAlignment.Center, TextAlignment = TextAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center };
string name = "TextBlock" + r.ToString();
myTextBlockr.Name = name;
ListBox list = new ListBox() { Height = 200, Width = 200 };
string k="list"+r;
list.Name = k;
}
我动态创建了列表框。我想控制它在其他函数中的可见性。我使用了 activator.createinstance 方法但它抛出异常。
public void myTextBlock1_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
string name = ((TextBlock)sender).Name;
// name.Substring(10,9);
string strl = "list" + name.Substring(9);
object obj = Activator.CreateInstance(typeof(ListBox), strl);
ListBox list = (ListBox)obj;
list.Visibility = Visibility.Visible;
}
它抛出以下异常 System.missingmethodexception 。
最佳答案
如果您以后需要引用它,请在您的类中保留对 ListBox 的引用。如果您正在创建多个列表框,请将它们添加到 Dictionary<string, ListBox>
这样您以后就可以通过按键查找它们。
public class Demo {
private Dictionary<string, ListBox> _listboxes = new Dictionary<string, ListBox>();
private void CreateListBoxWithName(string name) {
var lb = new ListBox();
_listboxes.add(name, lb);
// do other stuff ...
}
private ListBox FindListBoxByName(string name) {
return _listboxes[name];
}
}
关于c# - 在其他函数中控制动态创建的列表框属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23012396/