C# windows phone -Alignment in xaml ListBox.ItemTe

2020-07-13 08:50发布

i Would like to make simple ListBox. Each line should contain 2 controls, one aligned to the left the other to the right, thats all :) I tried multiple approaches but nothing worked. My code is following

<StackPanel Grid.Row="1" Margin="12,0,12,0" Grid.Column="0">
        <ListBox Name="ListBox" Margin="12,0,12,0" ItemsSource="Exercises" HorizontalContentAlignment="Stretch">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" Width=">
                        <TextBlock Text="abc" HorizontalAlignment="Left" VerticalAlignment="Center"/>
                        <TextBlock Text="def" HorizontalAlignment="Right" VerticalAlignment="Center"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </StackPanel>

(Two textblocks are just for demonstration, in real application i'd like to bind one text block to real data, instead of second ill use button.) When ill compile this, both textblock are aligned to the left, in emulator, it seems like one textblock with text "abcdef". Any idea how to align one text block to the right and the other one to the left? many thanks :)

1条回答
够拽才男人
2楼-- · 2020-07-13 09:20

By default the ListBoxItem does not fill the space it is given. It aligns itself and the content to the left. To ensure that the content of your ListBoxItem spans the entire width, you need to change the ItemContainerStyle

<ListBox>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

Now the content will span the available width. If you wish to use a StackPanel as in your example, make sure to set it's HorizontalAlignment also. The StackPanel also does not fill in the available space given

<DataTemplate>
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch">
        <TextBlock Text="abc" HorizontalAlignment="Left" VerticalAlignment="Center"/>
        <TextBlock Text="def" HorizontalAlignment="Right" VerticalAlignment="Center"/>
    </StackPanel>
</DataTemplate>

However, I would recommend using a Grid and defining two columns

<DataTemplate>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <TextBlock Text="abc" HorizontalAlignment="Left" VerticalAlignment="Center"/>
        <TextBlock Text="def" Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Center"/>
    </Grid>
</DataTemplate>
查看更多
登录 后发表回答