Search code examples
c#asp.netxamluwpuniversal

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>
            <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"/>
            </StackPanel>
        </StackPanel>
    </DataTemplate>

listview:(althought it might not be relevant.)

<ListView Name="PlayListView" ItemsSource="{x:Bind Playlists}"
                                      IsItemClickEnabled="True"
                                      ItemClick="PlayListView_ItemClick"
                                      ItemTemplate="{StaticResource PlaylistDataTemplate}"
                                      Visibility="Collapsed"
                                      Height="420"
ScrollViewer.VerticalScrollBarVisibility="Visible"/>

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)
    {
       ?????
    }

Solution

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