Search code examples
c#wpfxamllistviewexpander

How to select first item in expanded group (listview)


Can anyone help me with this problem (c# wpf):

I have a ListView with this Style for my Expander (for each group):

<ListView.GroupStyle>
    <GroupStyle>
        <GroupStyle.HeaderTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding Path=Name}" />
                </StackPanel>
            </DataTemplate>
        </GroupStyle.HeaderTemplate>
        <GroupStyle.ContainerStyle>
            <Style TargetType="{x:Type GroupItem}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type GroupItem}">
                            <Expander IsExpanded="False">
                                <Expander.Header>
                                    <StackPanel Orientation="Horizontal">
                                        <TextBlock Text="{Binding Path=Name}" />
                                    </StackPanel>
                                </Expander.Header>
                                <ItemsPresenter />
                            </Expander>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </GroupStyle.ContainerStyle>
    </GroupStyle>
</ListView.GroupStyle>

When the user expands the Expander, I would like to select the first item in the expanded group.

I added my group like this (CustomerOrderList = ListView):

CustomerOrderList.ItemsSource = OrderDetails.DefaultView;
CollectionView cv = (CollectionView)CollectionViewSource.GetDefaultView(CustomerOrderList.ItemsSource);
PropertyGroupDescription pgd = new PropertyGroupDescription("OrderInfo");
cv.GroupDescriptions.Add(pgd);

Is this possible?

Thanks, Senne


Solution

  • Yes it is possible.

    Include Linq namespace

     using System.Linq;
    

    Handle the Expander's Expanded event

      <Expander Expanded="GroupExpander_Expanded" IsExpanded="False" ... /> 
    

    Code Behind ...

       private void GroupExpander_Expanded(object sender, RoutedEventArgs e)
       {
            var expander = sender as Expander;
            //Extract the group 
            var groupItem = expander.DataContext as CollectionViewGroup;
            //Set the first item from the group to ListBox's Selected Item property.
            CustomerOrderList.SelectedItem = groupItem.Items.First();
       }
    

    If you are using MVVM then use the Attached Property behavior to wrap this functionality into it.

    Hope this helps,