我的代码动态添加包含按钮的 ListBoxes。按钮动态添加另一个按钮。嗯……这就是期望。我的代码不起作用。
这是我的代码:
public Button createElements(string nameOfElement)
{
if (nameOfElement.Contains("Floor"))
{
// code creating Button
return floorButton;
}
else if (nameOfElement.Contains("Sound"))
{
// code creating Button
return soundButton;
}
else if (nameOfElement.Contains("Add"))
{
// code creating Button
return addButton;
}
return null;
}
private ListBox addNewListBox(ListBox targetElement, int ex)
{
// vytvori ListBox do hlavniho ListBoxu
ListBox elementListBox = new ListBox();
elementListBox.Name = "elementListBox" + indexY;
elementListBox.VerticalAlignment = VerticalAlignment.Top;
elementListBox.ItemsPanel = (ItemsPanelTemplate)XamlReader.Parse("<ItemsPanelTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><StackPanel Orientation=\"Horizontal\"/></ItemsPanelTemplate>");
if (ex == 1)
{
targetElement.Items.Remove(addFloor);
targetElement.Items.Add(elementListBox);
elementListBox.Items.Add(createElements("Floor"));
elementListBox.Items.Add(createElements("Sound"));
elementListBox.Items.Add(createElements("Add"));
targetElement.Items.Add(addFloor);
indexY++;
indexX = 0;
}
return elementListBox;
}
这是最终功能的详细信息。
private void putElements(ListBox targetElement, Button targetObject)
{
targetElement.Items.Add(targetObject);
// there's problem
MessageBox.Show("targetElement: ", targetElement.Name);
MessageBox.Show("targetObject", targetObject.Name);
}
点击事件调用此函数:
putElements(addNewListBox(mainListBox, 0), createElements("Sound"));
MessageBoxes 在最后一个函数中打印对象的名称。对象是正确的,但是这一行:
targetElement.Items.Add(targetObject);
有问题-这条线什么也没做..
感谢帮助!!