Jan Zahradník
Jan Zahradník

Reputation: 2497

Size WPF Grid Columns equally inside ListBox

Inside ItemTemplate I need two columns, each 50% width. Provided text is longer and is not wrapped, but occupy more width than expected.

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Width="650">
    <ListBox x:Name="ListView">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>
                    <TextBlock TextWrapping="Wrap">
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce dapibus commodo dui vulput
                    </TextBlock>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Window>

To reproduce the sample you need call in code behind:

ListView.ItemsSource = new[] { new object() };

Upvotes: 0

Views: 452

Answers (1)

icebat
icebat

Reputation: 4774

TextBlock receives all the width it wants in this setup, with the second grid column going off screen if need be. You can limit the width of the inner Grid to force it to distribute only the space it has:

<DataTemplate>
    <Grid Width="{Binding ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox}}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <TextBlock TextWrapping="Wrap">
           Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce dapibus commodo dui vulput
        </TextBlock>
    </Grid>
</DataTemplate>

Upvotes: 2

Related Questions