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。
答案 0 :(得分:2)
如果您以后需要引用它,请在类中保留对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];
}
}