Jon Jon - 1 year ago 77
ASP.NET (C#) Question

Button placed on listitem, how to access said listitem in button eventhandler?

I'm making a playlist management app in UWP and I need to be able to do a number of operations on items in the listviews I have set up. I've attached buttons to the listitems, but I don't know how to reference the "parent" listitem in the eventhandler of the button.

For instance:

page resource:

<DataTemplate x:DataType="data:JonPlaylist" x:Key="PlaylistDataTemplate">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Name:" Foreground="Azure" VerticalAlignment="Bottom" HorizontalAlignment="Left" FontStyle="Italic" Margin="0,0,10,0"/>
<Button Name="DeletePlayListButton" Content="Delete" Foreground="Azure" Background="SteelBlue" BorderBrush="Azure" Click="DeletePlayListButton_Click"/>

listview:(althought it might not be relevant.)

<ListView Name="PlayListView" ItemsSource="{x:Bind Playlists}"
ItemTemplate="{StaticResource PlaylistDataTemplate}"

And the eventhandler for the deletebutton. This is where I'm stuck, I want to reference the listitem on which the button clicked was located.

private void DeletePlayListButton_Click(object sender, RoutedEventArgs e)

Answer Source

So if you're looking to get the bound JonPlaylist, if you're not changing the DataContext in the DataTemplate (which it appears you're not), you can get that like this:

    private void DeletePlayListButton_Click(object sender, RoutedEventArgs e)
        var button = sender as Button;
        if (button != null)
            var boundItem = button.DataContext as JonPlaylist;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download