简体   繁体   中英

Get id of selected item of ListView in Xamarin.Forms

This is my ListView :

 <ListView  Grid.Column="0" Grid.Row="1" ItemTapped="itemTapped" x:Name="listofEmployee" BackgroundColor="{x:Static color:ColorResources.listBackgroundColor}" IsVisible="false">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout BackgroundColor="#eee" Orientation="Vertical">
                            <StackLayout Orientation="Horizontal">
                                <Image x:Name="imgCheckUncheck" Source="btn_check_off.png" VerticalOptions="CenterAndExpand" HeightRequest="30" WidthRequest="30" >
                                    <Image.GestureRecognizers>
                                        <TapGestureRecognizer Tapped="OnImg_TapGestureRecognizerTapped" />  
                                    </Image.GestureRecognizers>
                                </Image>
                                <Label Text="{Binding empName}" VerticalOptions="CenterAndExpand" TextColor="{x:Static color:ColorResources.listTextColor}" />                               
                            </StackLayout>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

Model for this :

public  class empList_Model
{
    public string empName{ get; set;}
    public int Selected{ get; set;}
    public string id{ get; set;}
}
public static class empList_Data
{
    public static List<empList_Model> getData ()
    {
        return new List<empList_Model> {

            new empList_Model () {
                empName = "Bryan Garret",Selected=0,id="1"
            },

            new empList_Model () {
                empName = "James Simpson",Selected=0,id="2",
            },

            new empList_Model () {
                empName = "Kathryn Newer",Selected=0,id="3"
            },

            new empList_Model () {
                empName = "Amanda Stevens",Selected=0,id="4"
            },

        };
    }
}

By using above code I want to take some actions as below :

1)On image tap, set property selected=1 or selected=0 of class empList_Model.

2)On image tap, display property "id" in DisplayAlert() function.

You need to implement the "itemTapped" event in the code behind class as there is no command binding to the view model possible. This should look like this:

public void OmItemTapped (object o, ItemTappedEventArgs e)
    {
        var dataItem = e.Item as empList_Model;
        // now you can change the data item or trigger anything on the
        // view model and provide the tapped instance as parameter
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM