ListView is one of the controls we use the most in Xamarin. We must use the ListView to display the data we have received from any place on a regular basis. While using the ListView, we can also send data in any control we have included. Take a list of recipes, for example. Get the vegetables to be eaten in this listen. Be a button with which we can get information about these vegetables or fruits. When we click on this button, we will get the CommandParameter to know which of the vegetables is clicked.
First we will create a model called Vegetables to ensure that our data are always the same species. Vegetables name, calorie and price.
Once we have created the vegetable model, we can start designing. We will keep every vegetable we create in a sequential order in the ListView. Vegetable name, price and calorie will be displayed while showing on the screen. We will also put a search button on them for easy research.
Now we come to the CommandParameter limit. We will give the name of each of the vegetables as Buton CommandParameter. We will do this on xaml side. I will share the code for Design and CommandParameter here. Xaml party;
<StackLayout> <ListView x:Name="listeYemek" ItemsSource="{Binding .}" > <ListView.ItemTemplate> <DataTemplate> <ViewCell> <ViewCell.View> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Label Text="{Binding SebzeAd}" HorizontalTextAlignment="Center" Grid.Column="0" TextColor="Black"/> <Label Text="{Binding Kalori}" HorizontalTextAlignment="Center" Grid.Column="1" TextColor="Black"/> <Label Text="{Binding Fiyat}" HorizontalTextAlignment="Center" Grid.Column="2" TextColor="Black"/> <Button Text="Ara" BackgroundColor="Blue" TextColor="White" BorderWidth="2" BorderRadius="15" BorderColor="Red" x:Name="buttonAra" Grid.Column="3" Clicked="buttonAra_Clicked" CommandParameter="{Binding SebzeAd}"/> </Grid> </ViewCell.View> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView> </StackLayout>
After sending vegetables names with CommandParameter, we need to get these parameters in .cs. The button gets two variables from the outside in the click event. One of them is the sender. We take this button by casting it because it is a sender button. After that, we take the CommandParameter of the button and hold it in a variable. Finally, we succeed in this screen.
private void buttonAra_Clicked(object sender, EventArgs e) { Button btn = (Button)sender; var sebzead = btn.CommandParameter.ToString(); DisplayAlert("Sebze Adı", sebzead, "OK"); }
If you have any questions, you can reach us by email or comment.
Leave a Reply