我有一个 Windows Phone 8页面,左边是国家/地区名称,右边是ISD代码。我想将国家/地区名称与最左侧对齐,将ISD代码对齐到屏幕的最右侧。
为此,我写了以下XAML
<Grid x:Name="LayoutRoot" Background="Transparent">
<ListBox ItemsSource="{Binding IsdCodes}" HorizontalAlignment="Stretch" Background="Blue">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalAlignment" Value="Stretch"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch" Background="Yellow" ShowGridLines="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" HorizontalAlignment="Stretch" Text="{Binding Key}" />
<TextBox Grid.Column="1" HorizontalAlignment="Stretch" Text="{Binding Value}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
但我得到的输出如下:
当我将网格列宽度设为3 *和*时,我预计第一列占据屏幕左边和第二列宽度的75%,占据右边屏幕宽度的25%。但我确实看到列表框项目仍然没有占据整个屏幕宽度(假设从黄色背景)。
我哪里出错了?
答案 0 :(得分:3)
尝试将HorizontalContentAlignment
的{{1}}设为ListBoxItem
:
Stretch
答案 1 :(得分:1)
这是因为DataTemplate
是在ContentPresenter
中呈现的,ListBoxItem
未在ListBoxItem
中展开。您需要重新定义 ...
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
<ContentPresenter HorizontalAlignment="Stretch" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
...
的模板:
{{1}}
答案 2 :(得分:0)
如您所知,屏幕宽度为480,您可以将其分配为360和120
<ListBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch" Background="Yellow" ShowGridLines="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="360"/>
<ColumnDefinition Width="120" />
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" HorizontalAlignment="Stretch" Text="{Binding Key}" />
<TextBox Grid.Column="1" HorizontalAlignment="Stretch" Text="{Binding Value}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
答案 3 :(得分:0)
这可以帮助你,在listbox datatemplate
中设置网格的宽度<Grid x:Name="LayoutRoot" Background="Transparent">
<ListBox ItemsSource="{Binding IsdCodes}" HorizontalAlignment="Stretch" Background="Blue">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalAlignment" Value="Stretch"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Left" Background="Yellow" ShowGridLines="True" Width="460">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" HorizontalAlignment="Stretch" Text="{Binding Key}" />
<TextBox Grid.Column="1" HorizontalAlignment="Stretch" Text="{Binding Value}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>