【问题标题】:Dynamically added objects and work with them动态添加对象并使用它们
【发布时间】:2013-09-12 07:32:12
【问题描述】:

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

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

感谢您的帮助!

【问题讨论】:

    标签: c# wpf button listbox


    【解决方案1】:

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

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

    【讨论】:

    • 好的,那我怎样才能得到现有的ListBox呢?您知道,这就是问题所在,当您需要索引为 3 的 ListBox 时,但该列表框是动态添加的。我需要在动态添加的 ListBox 中添加按钮(动态添加按钮)。
    • 您指的是哪个现有的 ListBox?如果你想获得一个特定的动态添加的 ListBox,你可以给它们唯一的名称(例如,使用计数器),然后遍历 mainListBox 的项目以找到匹配的名称。
    猜你喜欢
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多