Expanders inside listbox leaving blank space on collapse

Posted by siz on Stack Overflow See other posts from Stack Overflow or by siz
Published on 2010-05-21T19:13:40Z Indexed on 2010/05/22 9:30 UTC
Read the original article Hit count: 189

Filed under:
|

We have a rather complex UI that is presenting some problems for us.

I have a ListBox that contains a set of DataItems. The DataTemplate for each item is an Expander. The header is text, the content of the Expander is a ListBox. The ListBox contains SubDataItems. The DataTemplate for each SubDataItem is an Expander.

Here is a simplified XAML in which I reproduce the issue:

  <ListBox ItemsSource="{Binding Items}">
    <ListBox.ItemTemplate>
      <DataTemplate>
        <Expander Header="{Binding Header}">
          <ListBox ItemsSource="{Binding SubItems}">
            <ListBox.ItemTemplate>
              <DataTemplate>
                <Expander Header="{Binding SubHeader}">
                  <Grid Height="40">
                    <TextBlock Text="{Binding SubText}" />
                  </Grid>
                </Expander>
              </DataTemplate>
            </ListBox.ItemTemplate>
          </ListBox>
        </Expander>
      </DataTemplate>
    </ListBox.ItemTemplate>
  </ListBox>

There is a problem with how the layout is produced. If any Expander corresponding to the SubDataItem is expanded, the ListBoxItem containing this ListBox (the Expander.Content in the parent DataTemplate) correctly requests more space. So I can expand all SubDataItems and correctly see my data. However, when I collapse, the space I previously asked to expand, remains blank, instead of being reclaimed by the ListBoxItem.

This is a problem because if I have say 10 SubDataItems and happen to expand all of them at the same time and then collapse, there is a significant amount of white space wasting my real estate.

How can I force WPF to resize the ListBoxItem to the correct state?

© Stack Overflow or respective owner

Related posts about c#

Related posts about wpf