Search code examples
wpfxaml

Listbox Data Template Text Overflow


I am working on a data template for a list box. One of the data bound fields contains a long description and I don't know how to make sure that the text just wraps at the edge of the list box item. This is my xaml code...

<ListBox x:Name="lstTest" ScrollViewer.HorizontalScrollBarVisibility="Disabled" HorizontalContentAlignment="Stretch">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <StackPanel Orientation="Vertical">
                    <Label Content="{Binding Path=Name}"></Label>
                    <TextBlock TextWrapping="Wrap"  Text="{Binding Path=Description}"></TextBlock>
                </StackPanel>
                <DockPanel LastChildFill="True">
                    <Label Content="{Binding Path=AuctionDate}"></Label>
                </DockPanel>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Sample Item...

new AuctionItem
{
    RecordId = 1,
    Name = "Auction G",
    Description = "Morbi eu nisl sed magna vestibulum ultrices quis eu enim. Nunc semper libero at tellus tincidunt eu elementum turpis rhoncus. Mauris condimentum semper pulvinar. Integer vel ante ipsum, at pulvinar sapien. Donec vestibulum ultricies dui sed viverra. Sed a augue diam, et mollis libero. Phasellus eget rutrum nibh.",
    AuctionDate = DateTime.Now
}

What I am asking is this even the correct structure for what I am trying to achieve? I would like the date to be on the right side of the item. I would like the name to be at the top left and bellow the name I would like the description. I can make the description fixed size but I would like the listbox items to resize with the listbox correctly.

I would appreciate any help you can provide with this...

Thank You!


Solution

  • Your problem is with the StackPanel.

    Remove it and replace it with a grid. It's been the source of grief for myself as well.

    I did something like to this to mimic your situation and it works for me:

    <Grid>
        <ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled">
           <ListBox.ItemTemplate>
              <DataTemplate>
                 <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition />
                        <ColumnDefinition Width="Auto" />
                    </Grid.ColumnDefinitions>
                    <TextBlock Text="{Binding RecordID}" />
                    <TextBlock Grid.Column="1" Text="{Binding Description}" TextWrapping="Wrap" />
                    <TextBlock Grid.Colunm="2" Text="{Binding AuctionDate}" />
                 </Grid>
              </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    <Grid>
    

    See this answer. And this answer as well.

    Good luck!