Search code examples
c#wpflistviewitem

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


I have some ListViewItems from a collection, I have created a DataTemplate so that each of ListViewItem has a Button as a child control:

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

When I click a certain Button, is there a way to change the IsSelected property of the ListViewItem that contains the clicked Button?


Solution

  • To change the IsSelected property of the ListViewItem that contains the clicked Button you should use the DataContext to find the item like this:

    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
    }