0

我正在尝试在 Listview 中的堆栈面板中垂直和水平居中对齐文本块,但我只能使文本垂直居中而不是水平居中。另外,文本没有被换行。这是我尝试过的代码:

 <ListBox Name="lstTiles" Margin="12,0,-12,0" Grid.Row="1" SelectionChanged="lstTiles_SelectionChanged">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <toolkit:WrapPanel/>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Background="{StaticResource PhoneAccentBrush}" Width="145" Height="80" Margin="8,8,0,0" Orientation="Vertical" >
                    <TextBlock Text="{Binding Name}" Tag="{Binding ID}" Style="{StaticResource PhoneTextNormalStyle}" FontSize="15" TextWrapping="Wrap" TextAlignment="Center" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

如何实现文本垂直、水平和文本换行?

4

1 回答 1

0

It looks like since you have the orientation of the StackPanel set to Horizontal, you're putting textblocks next to each other rather than on top of each other. Since the StackPanel elements take the size of their children, you would be able to visualize this as a horizontal, side-by-side, listing of textblocks. Since each textblock takes the size of the text that is in it, you are going to see blocks that are of varying widths, so centering horizontally is going to have no effect.

You could use margins (a pain) to accomplish equal widths. I don't recommend this.

You could also put grids of a set width in the stack panel, and put the textblocks on the grid. You may be able to set the width of the textblocks to get the right effect, but I can't test this at the moment, and I don't remember if it will cause the text to stretch or not.

For text wrapping, I assume you're talking about within the textblock, and that's easy - just set the textblock's TextWrapping property to Wrap.

Try setting the HorizontalContentAlignment and VerticalContentAlignment properties on the listboxitem. I don't have my dev computer now, so I can't experiment, but here is a post that might help you: Silverlight 3: ListBox DataTemplate HorizontalAlignment. Look at both of the first two answers, and see which one might be most helpful in your situation, substituting center, of course, in place of left, top, or stretch.

于 2012-06-29T13:48:01.757 回答