简体   繁体   中英

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

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

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