Michael
Michael

Reputation: 11

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>

Upvotes: 0

Views: 2159

Answers (1)

Keith Stein
Keith Stein

Reputation: 6754

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;
}

Upvotes: 4

Related Questions