我在Windows Phone应用程序中创建一个ListBox,使项目水平对齐。我希望如果有5个项目那么他们应该平均占用空间如果有2个项目在集合中应该相应地对齐占用总宽度/ 2空间。我如何实现这一点是我写的代码:
<ListBox x:Name="CarSelector" ItemsSource="{Binding listData}"
VerticalAlignment="Center" HorizontalAlignment="Stretch"
ScrollViewer.VerticalScrollBarVisibility="Disabled"
Background="White"
ItemContainerStyle="{StaticResource SelectorContainerStyle}"
Style="{StaticResource lstbxSelectorStyle}"
>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<Grid>
<i:Interaction.Behaviors>
<control:GridItemPanelBehavior />
</i:Interaction.Behaviors>
</Grid>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch"
>
<Image Height="56"
Width="56"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Source="{Binding id}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
行为:
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.LayoutUpdated += AssociatedObject_LayoutUpdated;
}
void AssociatedObject_LayoutUpdated(object sender, EventArgs e)
{
Grid gridItemPanel = AssociatedObject as Grid;
var childCount = gridItemPanel.Children.Count;
// add the required number of column definitions
for (int row = 0; row < childCount; row++)
{
gridItemPanel.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
}
// set the column property for each chid
for (int i = 0; i < childCount; i++)
{
var child = gridItemPanel.Children[i] as FrameworkElement;
Grid.SetColumn(child, i);
}
}