动态添加对象并使用它们

时间:2013-09-12 07:32:12

标签: c# wpf button listbox

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

有问题 - 这条线无所事事。

感谢您的帮助!!

1 个答案:

答案 0 :(得分:0)

如果ex值为1,您只需将新ListBox添加到mainListBox,但在您的情况下为0。

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

相关问题