1

我总是在 windows phone 中定位元素时遇到问题。希望有人可以帮助我:我有一个从后面的代码动态填充的列表框:

<ListBox Name="list" Grid.Row="1" HorizontalAlignment="Center">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}"  Style="{StaticResource list_service_item}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>

样式在 App.xaml 中定义:

<Style x:Key="list_service_item" TargetType="TextBlock">
        <Setter Property="FontSize" Value="25"/>
        <Setter Property="FontWeight" Value="Bold"/>
        <Setter Property="Foreground" Value="Peru" />
        <Setter Property="TextWrapping" Value="Wrap"/>
        <Setter Property="HorizontalAlignment" Value="Center"/>
        <Setter Property="Margin" Value="0 0 0 5"/>
    </Style>

并且看起来工作正常,除了对齐属性。

如果列表框项目的长度相同,则一切正常,但如果其中一个较长,则其他所有项目都将自己对齐到较长项目的开头而不是保持居中:

在此处输入图像描述

我该如何解决这个问题?

4

2 回答 2

1

您需要使每个 ListBoxItem 的 ItemContainer 拉伸到 ListBox 的宽度:

<ListBox.ItemContainerStyle>
  <Style TargetType="ListBoxItem">
    <Setter Property="HorizontalContentAlignment"
            Value="Stretch" />
  </Style>
</ListBox.ItemContainerStyle>
于 2013-10-09T13:37:58.243 回答
0

如何使用该TextBlock.TextAlignment物业?:

<Style x:Key="list_service_item" TargetType="TextBlock">
    <Setter Property="FontSize" Value="25" />
    <Setter Property="FontWeight" Value="Bold" />
    <Setter Property="Foreground" Value="Peru" />
    <Setter Property="TextWrapping" Value="Wrap" />
    <Setter Property="HorizontalAlignment" Value="Center" />
    <Setter Property="TextBlock.TextAlignment" Value="Center" /><!--<<< Used here-->
    <Setter Property="Margin" Value="0 0 0 5"/>
</Style>

免责声明:这适用于 WPF,但我不能保证它适用于 Windows Phone 8

更新>>>

好的,在看到您的照片后,我同意它没有按您的预期工作。但是,我认为这可能更多的是物品放置不正确的情况。你可以试试这个:

<ListBox HorizontalContentAlignment="Center" ... />

如果这不起作用,您可以尝试将该属性设置为,Stretch以便项目填充空间,然后可以使TextBlocks 居中:

<ListBox HorizontalContentAlignment="Stretch" ... />
于 2013-10-09T11:15:17.177 回答