Search code examples
wpflistviewscrollexpander

Cant scroll an ListView that contains an Expander and an ItemControl WPF


So I am trying to make a little shopping list app for the family, but I cant figure out what I am doing wrong. When I have a list of Items that goes off the screen when you expand the expanders, the ListBox does not allow me to scroll.

The Code is:

<StackPanel>
        <ListView Name="ListView" ItemsSource="{Binding}" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
            <ListView.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Add" Click="AddClick" />
                    <MenuItem Header="Edit" Click="EditClick" />
                    <MenuItem Header="Delete" Click="DeleteClick" />
                </ContextMenu>
            </ListView.ContextMenu>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Expander Header="{Binding Name, Mode=TwoWay}">
                        <ItemsControl ItemsSource="{Binding Ingredients, Mode=TwoWay}" IsEnabled="False">
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <template:IngredientsTemplate IsEnabled="False"/>
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>
                    </Expander>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackPanel>

Any help or suggestions would be appreciated!!!


Solution

  • The problem is the parent StackPanel. WPF layout controls work by first querying their children to determine how much space is needed, then applying the layout logic, then telling each child how much space they've actually been allocated. During the layout process that StackPanel is asking the ListView how much space it wants, to which the ListView responds with all the space it needs to display all the elements it has, and so the StackPanel sets its own size to encompass all that required space.

    To fix this you're going to have to replace that StackPanel with something like a Grid (say) and/or re-think how you do your layout.