Smirti
Smirti

Reputation: 305

Adjust ListBox items width based on its content

<ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid   Rows="1" >                    
            </UniformGrid>                    
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBoxItem HorizontalContentAlignment="Stretch">listbox item 1</ListBoxItem>
    <ListBoxItem>listbox item 2</ListBoxItem>
    <ListBoxItem>listbox item 3</ListBoxItem>
    <ListBoxItem>listbox item 4</ListBoxItem>
    <ListBoxItem>listbox item 5</ListBoxItem>
</ListBox>

I have added ListBoxItems as above and used UniformGrid to display it. but I can't achieve content based width for each of the list box item. I have tried HorizontalContentAlignment as Stretch and Auto width properties. Nothing happened.

Upvotes: 0

Views: 149

Answers (1)

thatguy
thatguy

Reputation: 22129

You have to use HorizontalAlignment instead of HorizontalContentAlignment.

<ListBoxItem HorizontalAlignment="Left">listbox item 1</ListBoxItem>

If you want to set the alignment for all items, consider creating an item container style.

<ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled">
   <ListBox.ItemContainerStyle>
      <Style TargetType="{x:Type ListBoxItem}">
         <Setter Property="HorizontalAlignment" Value="Left"/>
      </Style>
   </ListBox.ItemContainerStyle>
   <!-- ...your code. -->
</ListBox>

Please note that the default value for HorizontalAlignment is already Stretch, so you will not see a difference there. Furthermore, there is no Auto. The possible values are Left, Right, Center and Stretch. All values except for Stretch will size to the content.

Upvotes: 0

Related Questions