C# 如何通过Foreach创建按钮?
我想通过Foreach创建许多按钮,这些按钮打印Uri的属性。但我不知道怎么做。你能告诉我怎么做吗? 这是我的代码:C# 如何通过Foreach创建按钮?,c#,windows-phone-7,C#,Windows Phone 7,我想通过Foreach创建许多按钮,这些按钮打印Uri的属性。但我不知道怎么做。你能告诉我怎么做吗? 这是我的代码: private void CreateButtons() { Uri uri = new Uri("/Pages/PageTest.xaml?Name=Stephen&Age=17",UriKind.Relative); foreach(var pi in typeof(Uri).GetProperties()) { //crea
private void CreateButtons()
{
Uri uri = new Uri("/Pages/PageTest.xaml?Name=Stephen&Age=17",UriKind.Relative);
foreach(var pi in typeof(Uri).GetProperties())
{
//create button
Button btn = new Button();
btn.Content = pi.Name;
btn.Margin = new Thickness(0,0,0,12);
//i think this is bug, but i don't know,how to do
btn.Click += (se,ev)=>
{
MessageBox.Show(pi.GetValue(btn,null).ToString());
}
stackPanel.Children.Add(btn);
}
}
您使用的目标不正确 pi.GetValue(btn,null) 您正在查询URI属性,但目标是按钮对象 你需要像这样的东西:
MessageBox.Show(pi.GetValue(uri, null).ToString());
我猜您在事件处理程序中遇到异常 尝试在抛出异常时启用中断(调试|异常->检查公共语言运行时异常旁边的“抛出”)
然后在附加调试程序的情况下运行,查看单击按钮时发生的情况。我怀疑出现NullPointerException是否有错误?是否显示任何按钮?猜测一下,您可能正在同一位置创建按钮,因此一个按钮绘制在其他按钮之上。Ui是正确的,我有许多按钮,但当我单击其中一个按钮时,它什么都没有要执行…我知道,
MessageBox.Show(pi.GetValue(btn,null.ToString());
is的运行您是否尝试过按描述的方式运行?是否遇到异常?