I have a pretty straight forward question.
With this code, I create new entries whenever i click a button:
XAML
<Button Text="Add Ingredient" Grid.Row="1" Clicked="Button_Clicked"/>
Code-behind
private void Button_Clicked(object sender, EventArgs e)
{
AddEntry(EntriesStackLayout, "Ingredient " x.ToString());
x ;
}
private void AddEntry(StackLayout sl, string name)
{
Entry entry = new Entry()
{
Placeholder = name,
};
sl.Children.Add(entry);
}
I want to know what could I do to then remove these entries in order. For last to first?
This is what the app looks like:
CodePudding user response:
To remove an element from a layout
sl.Children.Remove(element);
If you don’t already have a reference to the element
var element = sl.Children.LastOrDefault();
CodePudding user response:
I want to know what could I do to then remove these entries in order. For last to first?
For your problem, you can remove the last element one by one in your StackLayout(EntriesStackLayout
).
Please refer to the following code:
private void Button_Clicked_Remove(object sender, EventArgs e)
{
var element = EntriesStackLayout.Children.LastOrDefault();
if (element!=null) {
EntriesStackLayout.Children.Remove(element);
}
}
YouPage.xaml
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="Fill">
<StackLayout Orientation="Horizontal" HorizontalOptions="Center" VerticalOptions="Center">
<ContentView Padding="0,40,0,40" VerticalOptions="FillAndExpand">
<Label Text="EasyChef" TextColor="Black" FontSize="24" FontAttributes="Bold" Margin="10"/>
</ContentView>
</StackLayout>
</StackLayout>
<ScrollView Grid.Row="1">
<StackLayout Orientation="Vertical" Padding="30,24,30,24" Spacing="10">
<Label Text="Simply select ingredients!" FontSize="Title"/>
<StackLayout x:Name="EntriesStackLayout">
<Grid VerticalOptions="CenterAndExpand" Margin="20" RowSpacing="20">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Entry Placeholder="Eg. Eggs" x:Name="EntryTag" Grid.Row="0"/>
</Grid>
</StackLayout>
<Button Text="Add Ingredient" Grid.Row="1" Clicked="Button_Clicked"/>
<Button Text="Relete Ingredient" Grid.Row="1" Clicked="Button_Clicked_Remove"/>
<CheckBox />
</StackLayout>
</ScrollView>
</Grid>
Note:
Make sure to add a null judgement, or the app may crash:
if (element!=null) {
EntriesStackLayout.Children.Remove(element);
}