Search code examples
wpfitemtemplate

WPF: Horizontally aligned collection with items of uniform width


I have a variable number of items bound from view model that need to be displayed horizontally and be selectable. Each item is represented by a text, these texts vary in length. When I use a list view with a StackPanel with horizontal orientation as its ItemTemplate, the items are only as wide as the text inside. Is there a way to make them all the same size, meaning the size of the widest one? Ideally without some complex codebehind, using item templates and such? Note: I can't set some arbitrary minimum width, because I don't know what length the texts can ultimately have (different languages etc)


Solution

  • you can use ListBox which has selection support with UniformGrid as ItemsPanel. UniformGrid will allocate equal space for each element

    <ListBox>
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid Rows="1"/>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
    
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Label Content="{Binding}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    

    example

    uniform