简体   繁体   中英

Get the value of a ListView item with button click

I have a ListView that gets its values from a database, with the last column being buttons. What I am trying to do, is that when a button is clicked, the value of the Name in the same row will be returned. Here's the relevant part of my XAML code:

        <Grid Grid.ColumnSpan="2">
            <ListView Name="PeopleList">
                <ListView.View>
                    <GridView>
                        <GridViewColumn Header="Name" DisplayMemberBinding="{Binding [Name]}" />
                        <GridViewColumn Header="Phone" DisplayMemberBinding="{Binding [Phone]}" />
                        <GridViewColumn Header="Email" DisplayMemberBinding="{Binding [Email]}" />

                        <GridViewColumn Header="Actions" Width="200">
                            <GridViewColumn.CellTemplate>
                                <DataTemplate>
                                    <Button Content=">" Click="ActionButton_Click"/>
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                        </GridViewColumn>
                    </GridView>
                </ListView.View>
            </ListView>
        </Grid>

You should be able to get the exact Button that was clicked from the sender argument of the Click event. From there you should be able to get Button.DataContext , which would hold a reference to the item that is being displayed on that row.
It would be something like:

private void ActionButton_Click(object sender, EventArgs args)
{
  var rowItem = (sender as Button).DataContext as People;
  string name = rowItem.Name;
}

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