为什么按钮不是水平对齐堆栈面板?

时间:2015-03-02 22:57:07

标签: wpf mvvm-light

我有一个从数据生成的按钮列表,因此有可变数量的按钮。在我正在进行大修的旧版软件中,他们使用了随机自定义控件,但结果是有一个无限增长的水平卷轴。

看起来我有完全相同的XAML,但没有水平对齐每个项目,只是垂直对齐

only goes vertically

<ScrollViewer Background="#33FFFFFF" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Disabled" >
    <StackPanel Orientation="Horizontal">
        <ItemsControl ItemsSource="{Binding Events}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button Margin="10" HorizontalAlignment="Stretch" Background="#FF1B1B1B" BorderThickness="5" BorderBrush="White" Command="{Binding Source={StaticResource Locator}, Path=EventSelector.ViewEventCommand}" CommandParameter="{Binding }">
                        <Grid Name="tileGridButton" Height="600" Width="400" Margin="5">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="5*"></RowDefinition>
                                <RowDefinition Height="5*"></RowDefinition>
                            </Grid.RowDefinitions>
                            <Border Grid.Row="0" Name="tileImageBorder" Margin="5" BorderThickness="1" VerticalAlignment="Stretch" HorizontalAlignment="Center">
                                <Image Name="tileImage" Margin="0" Source="{Binding ImageURL}"/>
                            </Border>
                            <Grid Grid.Row="1" VerticalAlignment="Top">
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="6*"></RowDefinition>
                                    <RowDefinition Height="4*"></RowDefinition>
                                </Grid.RowDefinitions>
                                <TextBlock Grid.Row="0" Name="tileText" Margin="5" Foreground="White" TextAlignment="Center" TextTrimming="CharacterEllipsis" TextWrapping="Wrap" FontSize="30" FontWeight="Bold" Text="{Binding Title}" />
                                <TextBlock Grid.Row="1" Name="tileDescription" Margin="5" Foreground="White" TextAlignment="Center" TextTrimming="CharacterEllipsis" TextWrapping="Wrap" FontSize="25" FontWeight="Bold" Text="{Binding EventTimeBegin}" />
                            </Grid>
                        </Grid>
                    </Button>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </StackPanel>
</ScrollViewer>

1 个答案:

答案 0 :(得分:5)

首先,你的 StackPanel 几乎没用,因为它只包含一个项目 ItemsControl

相反,您需要更改 ItemsControl ,以便它使用 StackPanel 作为在 ItemsControl 中布置项目的方法...

<ItemsControl ...>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        <ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
    .....