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

Mat*_*han 2 wpf mvvm-light

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

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

只是垂直

<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>
Run Code Online (Sandbox Code Playgroud)

Phi*_*ght 5

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

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

<ItemsControl ...>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        <ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
    .....
Run Code Online (Sandbox Code Playgroud)