Stretching controls to fill ItemsControl

Gregyski picture Gregyski · Aug 13, 2009 · Viewed 14k times · Source

I am attempting to write a simple WPF learning project which creates a set of buttons inside a resizeable main window. There is to be one Button per entry in a collection, and the contents of that collection may vary during run-time. I want the buttons to fill the entire window (e.g. 1 button @ 100% width, 2 buttons @ 50% width, 3 buttons @ 33% width, etc. all at 100% height). A simplified version of what I've written so far is:

<ItemsControl x:Name="itemscontrolButtons" ItemsSource="{Binding}">
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <Button Tag="{Binding}">
        <TextBlock Text="{Binding}" />
      </Button>
    </DataTemplate>
  </ItemsControl.ItemTemplate>
  <ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
      <StackPanel Orientation="Horizontal" />
    </ItemsPanelTemplate>
  </ItemsControl.ItemsPanel>
</ItemsControl>
...    
List<string> listButtonTexts = new List<string>() { "Button1", "Button2" };
...
itemscontrolButtons.DataContext = listButtonTexts;

This results in this:

alt text

I have been unable to make the buttons stretch to fit the width and my attempts to use a Grid instead of StackPanel were fruitless.

Then, as an optional improvement, I would appreciate suggestions on how to adjust it such that if there are so many buttons that they cannot fit properly on a line or are narrower than a threshold, it will wrap onto a new line (thereby halving the button heights if going from 1 to 2 rows).

I'd like to emphasize that I'd like to know how to do this the WPF way. I realize I can consume window resize messages and resize the controls explicitly, and that's how I'd have done it with MFC or WinForms, but from what I've read that is not how such things should be done with WPF.

Answer

Nir picture Nir · Aug 13, 2009

Replace the item control's panel with a UniformGrid, this will size all children so everything fits exactly:

<ItemsControl>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Rows="1"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>