Press ESC to close

ListView Using Command Parameter

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;

        <ListView x:Name="listeYemek"
                 ItemsSource="{Binding .}"
                                    <ColumnDefinition Width="*"/>
                                    <ColumnDefinition Width="*"/>
                                    <ColumnDefinition Width="*"/>
                                    <ColumnDefinition Width="*"/>
                                <Label Text="{Binding SebzeAd}"
                                <Label Text="{Binding Kalori}"
                                <Label Text="{Binding Fiyat}"
                                <Button Text="Ara"
                                        CommandParameter="{Binding SebzeAd}"/>

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

Your email address will not be published. Required fields are marked *