0

我的代码动态添加包含按钮的 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);

有问题-这条线什么也没做..

感谢帮助!!

4

1 回答 1

0

mainListBox如果 ex-value 为 1,您只是将新的 ListBox 添加到您的,但在您的情况下它是 0。

因此,您的新 ListBox (targetElementin putElements-方法)将永远不会添加到您的列表中mainListBox,因此不会显示。这就是为什么targetElement.Items.Add(targetObject);似乎不起作用。

于 2013-09-12T09:38:49.417 回答