Not able to find ToggleButton in CollectionViewGroup Not able to find ToggleButton in CollectionViewGroup wpf wpf

Not able to find ToggleButton in CollectionViewGroup


First of all, things will be a lot easier if we name the ToggleButton so that we can later use the ControlTemplate.FindName method. So here's the ToggleButton:

<ToggleButton x:Name="PART_ToggleButton"              Checked="{Binding IsFavourite}"              HorizontalAlignment="Right" />

What we need now is to get our hands on the templated container (a GroupItem control). For that we can use the ListView.ItemContainerGenerator.ContainerFromItem method.

Knowing that here's a piece of code that should retrieve the ToggleButton in question:

//we assume listView is a reference to the ListViewvar playingListSource = (ListCollectionView)listView.ItemsSource;//first we iterate over the top-level groupsforeach (CollectionViewGroup nationGroup in playingListSource.Groups){    //second-level groups are items of their parents    foreach (CollectionViewGroup leagueGroup in nationGroup.Items)    {        //first we retrieve the GroupItem control associated with current second-level group        var container = listView.ItemContainerGenerator.ContainerFromItem(leagueGroup) as GroupItem;        //then we find the named ToggleButton inside the template        var toggleButton = container.Template.FindName("PART_ToggleButton", container) as ToggleButton;        //at this point we have a reference to the ToggleButton    }}