Search code examples
wpfxamlitemscontrollistboxitem

ItemsControl/ListBox items exceed available width


I want text in column 3 wrap and have no horizontal scrollbar. Why doesn't this work?

<ItemsControl x:Name="listMessages" ItemsSource="{Binding Messages}" Grid.IsSharedSizeScope="True">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" SharedSizeGroup="Column1"/>
                    <ColumnDefinition Width="Auto" SharedSizeGroup="Column2"/>
                    <ColumnDefinition Width="*" SharedSizeGroup="Column3"/>
                    <ColumnDefinition Width="Auto" SharedSizeGroup="Column4"/>
                </Grid.ColumnDefinitions>
                <TextBlock Grid.Column="0" Text="Text1" />
                <TextBlock Grid.Column="1" Text="Text2" />
                <TextBlock Grid.Column="2" Text="Very long text that should wrap to the next line, but it doesn't work" TextWrapping="Wrap"/>
                <TextBlock Grid.Column="3" Text="Text4" />
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Items take more width than is available to ItemsControl. Same problem is with ListBox.

I tried to add ScrollViewer.HorizontalScrollbarVisibility=Disabled both on ItemsControl and Grid, but this doesn't help.


Solution

  • The text will be wrapped if you don't set the SharedSizeGroup property:

    <ColumnDefinition Width="*"/>
    

    Text wrapping and shared size groups don't go well together. You may want to specify a fixed MaxWidth for the ColumnDefinition or the TextBlock.