Search code examples
xamlwindows-phone-8.1windows-phonetextblock

Windows phone 8.1 Textblock width to Fill


I want to create the layout as shown in the following image's first section. But with the code attached, I can only get the layout output as show in the bottom section of the image attached.

enter image description here

    <ListView Grid.Row="1"
              ItemsSource="{Binding Items}"
              Margin="0,20,0,0">
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="40" />
                        </Grid.ColumnDefinitions>

                        <TextBlock TextWrapping="NoWrap"
                                   TextTrimming="WordEllipsis"
                                   Grid.Column="0"
                                   Text="{Binding Name}"
                                   Style="{ThemeResource ListViewItemTextBlockStyle}" />

                        <Image Grid.Column="1"
                               Source="image.png"/>

                    </Grid>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

Solution

  • You don't need the StackPanel in the DataTemplate - the Grid you have is enough for this.

    Also, in order to get the items to stretch, define a simple ListView.ItemContainerStyle in your ListView:

    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
        </Style>
    </ListView.ItemContainerStyle>
    

    So, full code:

    <ListView Grid.Row="1"
              ItemsSource="{Binding Items}"
              Margin="0,20,0,0">
        <ListView.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="40" />
                    </Grid.ColumnDefinitions>
    
                    <TextBlock TextWrapping="NoWrap"
                               TextTrimming="WordEllipsis"
                               Grid.Column="0"
                               Text="{Binding Name}"
                               Style="{ThemeResource ListViewItemTextBlockStyle}" />
    
                    <Image Grid.Column="1"
                           Source="image.png"/>
    
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>
        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="HorizontalContentAlignment" Value="Stretch" />
            </Style>
        </ListView.ItemContainerStyle>
    </ListView>