I am trying to make multiple buttons (add and remove) which both use a counter to add a number. The amount of buttons depends on how many people are in the list, they should also be different for every person.
My main problem is getting all the buttons instead of just the last one made, I am also expecting that the counter will use every button instead of the button designed for that counter.
This is my first time using MAUI and I can’t seem to find anything to help me with my problem.
private void CreateButton()
{
string names = "1;2;3";
var list = names.ToString().Split(';');
for (int i = 0; i < list.Length; i++)
{
Label lblName = new Label { Text = list[i].ToString() };
var counter = 0;
Label lblCounter = new Label
{
Text = $": {counter}",
};
Button btnAdd = new Button
{
Text = $"{list[i]}: add",
BackgroundColor = Colors.Green,
BorderColor= Colors.Black,
Command = new Command
(
execute: async() =>
{
counter += 1;
lblCounter.Text = $": {counter.ToString()}";
}
)
};
Button btnRemove = new Button
{
Text = $"{list[i]}: remove",
BackgroundColor = Colors.Red,
BorderColor = Colors.Black,
Command = new Command
(
execute: async () =>
{
counter -= 1;
if (counter <= 0)
{
counter = 0;
}
lblCounter.Text = $": {counter.ToString()}";
}
)
};
Content = new StackLayout
{
Children =
{
lblName, btnAdd, lblCounter, btnRemove
}
};
}
}
This is the full code for creating the buttons, it only creates the one for number 3.
>Solution :
The problem here is that you set the Content of your View or Page inside of the loop, which means that you’re replacing it with each iteration.
To fix this, you need to Add() the items to the StackLayout.Children instead of replacing the content with a new one every time:
private void CreateButton()
{
string names = "1;2;3";
var list = names.ToString().Split(';');
var stackLayout = new StackLayout();
for (int i = 0; i < list.Length; i++)
{
Label lblName = new Label { Text = list[i].ToString() };
var counter = 0;
Label lblCounter = new Label
{
Text = $": {counter}",
};
Button btnAdd = new Button
{
Text = $"{list[i]}: add",
BackgroundColor = Colors.Green,
BorderColor= Colors.Black,
Command = new Command
(
execute: async() =>
{
counter += 1;
lblCounter.Text = $": {counter.ToString()}";
}
)
};
Button btnRemove = new Button
{
Text = $"{list[i]}: remove",
BackgroundColor = Colors.Red,
BorderColor = Colors.Black,
Command = new Command
(
execute: async () =>
{
counter -= 1;
if (counter <= 0)
{
counter = 0;
}
lblCounter.Text = $": {counter.ToString()}";
}
)
};
stackLayout.Children.Add(lblName);
stackLayout.Children.Add(lblCounter );
stackLayout.Children.Add(btnAdd);
stackLayout.Children.Add(btnRemove);
}
Content = stackLayout;
}
I think you can also directly add items to the stackLayout using the Add() extension method:
stackLayout.Add(btnAdd);