views:

192

answers:

2

How can I make a silverlight listbox have all items be the same size and have them take up 100% of the listbox height. I.e. 1 item would be the height of the listbox, 2 items would each be 50% of the height of the list box, etc...

Edit - Here is the code

public class UniformPanel : Panel
{
    protected override Size MeasureOverride(Size availableSize)
    {
        Size panelDesiredSize = new Size();

        for (int i = 0; i < Children.Count; i++)
        {
            UIElement child = Children[i];
            child.Measure(availableSize);
            var childDesiredSize = child.DesiredSize;
            panelDesiredSize.Height += childDesiredSize.Height;
            if (panelDesiredSize.Width < childDesiredSize.Width)
            {
                panelDesiredSize.Width = childDesiredSize.Width;
            }
        }

        return panelDesiredSize;
    }
    protected override Size ArrangeOverride(Size finalSize)
    {
        double height = finalSize.Height/Children.Count;
        for (int i = 0; i < Children.Count; i++)
        {
            UIElement child = Children[i];
            Size size = new Size(finalSize.Width, height);
            child.Arrange(new Rect(new Point(0, i * height), size));
        }
        return finalSize; // Returns the final Arranged size
    }
}
+1  A: 

I see, your requirement is just to make each item get TotalHeight/itemsCount right.. In that case you can do the trick with UniformGrid(which is already there as part of the platform) by making Columns=1 Use the following XAML

        <ListBox VerticalContentAlignment="Stretch"  HorizontalContentAlignment="Stretch">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid IsItemsHost="True" Columns="1"/>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
          <Button />
          <Button />
          <Button />
    </ListBox>

UPDATE : silverlight doesnt have a UniformGrid, but you can get one I ported from WPF to Silverlight here

Jobi Joy
A: 

I don't think this is going to be trivial, in that the list box has an infinite height, add enough items, the scroll bar can show and the height of the contents grows.

The rendersize.height of the list box will let you ascertain what your available height is and then tell the child items to resize, but Jobi is right in that you are then best encapsulating all of that within a custom panel. The child items also need to accept being resized, and not used fixed height that can not be overriden.

In theory each child could check the parents rendered height and items count to then give it a percentage of the rendered height it may use and resize appropriately, but messy comes to mind.

Andrew