Anthony
Anthony

Reputation: 5226

Silverlight 2: Want a variable number of items to take up a fixed width

The stackpanel is not co-operating. We have a fixed width, and a variable number of items to lay out left-to-right inside it.

We have a an items control that lays them out with a stack panel:

<ItemsControl x:Name="testItems"
              HorizontalAlignment="Left"
              VerticalAlignment="Top">
    <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Stacktest:ItemControl />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

But this doesn't size the items correctly. They are always the same size, regardless of how much space is available. If there are too many items they are cut off on the right, rather than sized so that they all fit in. Any idea how to accomplish this? I'd use a grid if the number of items was constant, but it isn't. It's typically 1-4 items.

It would be nice if the ItemsPanelTemplate could be a grid with a variable number of columns. But I don't know if that (or something with the same result) is possible in an ItemsPanelTemplate.

Is the answer to write a special subclass of panel that allocates equal width to contained items?

Upvotes: 0

Views: 543

Answers (2)

pearcewg
pearcewg

Reputation: 9613

I'm probably a little old school, but I like doing this type of thing myself. You can write a little code on the backend to drop a dynamic number of items in the space (with a grid), and make them a dynamic width and evenly spaced.

This would likely work the way you want, and be tweakable.

Upvotes: 1

Denis Troller
Denis Troller

Reputation: 7501

I think what you want is the UniformGrid. You can indicate that it has one row, and it should layout all items inside to have the same width. This may not exactly be what you are looking for, but that's the closest I can think of.

I'm not sure if the Silverlight Toolkit offers such a component, but I've seen posts that show how to build one.

Jeff Wilcox's blog for example has one.

Upvotes: 1

Related Questions