MonoGame.Extended.Gui - variable number of items

Hello! I just started using MonoGame.Extended.Gui and am trying to display a variable number of buttons. So far, my code looks like this:

        ControlCollection buttons = new ControlCollection();
        for (int i = 0; i < actions.Length; i++)
        {
            IActionable action = actions[i];
            buttons.Add(new Button
            {
                Content = action.Name
            });
        }

        Screen screen = new Screen
        {
            Content = new DockPanel
            {
                LastChildFill = false,
                Items =
                {
                    new StackPanel { Items = buttons }
                }
            }
        };

but it doesn’t compile, saying that ItemsControl.Items is readonly. Any pointers as to what I’m missing would be appreciated!

Items is a collection that you add items to, you don’t instantiate it. I think it should be something like:

StackPanel panel = new StackPanel();
panel.Items.Add(buttons);

Items.Add(panel);
1 Like

That worked! Quick follow-up: I’m wondering why this doesn’t work for updating the content of a screen:

((ItemsControl)_screen.Content).Items.Insert(0, buttons);

nor does this:

DockPanel content = (DockPanel) _screen.Content;
content.Items.Insert(0, buttons);
_screen.Content = content;

but the following does? It seems kind of hacky.

DockPanel content = new DockPanel
{
    LastChildFill = false,
    Items = { buttons }
};

foreach (var item in ((ItemsControl)_screen.Content).Items)
{
    content.Items.Add(item);
}

_screen.Content = content;

I’m not seeing an obvious reason when Insert is not working. I’d suggest trying AddRange and see if that solves the problem.

Ah, to clarify, buttons isn’t a list - it’s a single StackPanel. And it looks like ControlCollection doesn’t define AddRange.