如何从其子控件访问 ListViewItem?

How can I get access to ListViewItem from its child control?

我有一些来自集合的 ListViewItem,我创建了一个 DataTemplate,这样每个 ListViewItem 都有一个 Button 作为子控件:

<Window.Resources>
    <DataTemplate x:Key="ItemTemplate_AwesomeTemplate">
        <StackPanel Orientation="Vertical" VerticalAlignment="Stretch">
            <Button Content="Awesome Button" Click="Awesome_Button_Click" HorizontalContentAlignment="Center" VerticalAlignment="Bottom" FontWeight="Bold" Foreground="Black"/>
        </StackPanel>
    </DataTemplate>
</Window.Resources>

<ListView x:Name="AwesomeListView" HorizontalAlignment="Left"  Height="577" VerticalAlignment="Top" Width="934" ScrollViewer.HorizontalScrollBarVisibility="Visible" Foreground="Black" Margin="10,10,0,0">
  <ListView.View>
    <GridView>
       <GridViewColumn Header="AwesomeHeader" Width="250" CellTemplate="{StaticResource ItemTemplate_AwesomeTemplate}"/>
    </GridView>
  </ListView.View>
</ListView>

当我单击某个 Button 时,有没有办法更改包含单击的 ButtonListViewItemIsSelected 属性?

要更改包含单击的 ButtonListViewItem 属性,您应该使用 DataContext 找到这样的项目:

private void Awesome_Button_Click(object sender, RoutedEventArgs e)
{
     var item = (sender as Button).DataContext;
     int index = AwesomeListView.Items.IndexOf(item);//find the index of the item that contains the clicked button
     AwesomeListView.SelectedItem = AwesomeListView.Items[index];//set the AwesomeListView's SelectedItem to item that contains the clicked button
}