ItemsControl中的StackPanel:Netflix海报样式

时间:2017-08-01 20:30:24

标签: xaml uwp-xaml

我希望在展示电影海报时有像Netflix这样的布局:

分类

海报1海报2海报3

第2类

海报1海报2海报3

我想出了这个:

<ItemsControl Name="dataControl" ItemsSource="{Binding}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Width="100" Height="50" FontSize="14" Text="{Binding Key}"></TextBlock>
                    <ItemsControl Name="dataControl" ItemsSource="{Binding Value}">
                        <ItemsControl.ItemTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal">
                                    <Button Content="{Binding MovieName}" Width="100" Height="100"/>                                        
                                </StackPanel>
                            </DataTemplate>
                        </ItemsControl.ItemTemplate>
                    </ItemsControl>
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

它绑定到一个字典,这就是为什么你有Key和Value作为控件的绑定。可悲的是,最终的结果是:

Wrongly aligned posters

请注意,“电影海报”不是水平对齐,而是垂直对齐。

似乎每个“行”创建一个项目的堆栈,但我不知道如何告诉它为所有相关项目创建一个水平堆栈。

这是来源:

Dictionary<string, List<Movie>> Source;

这是电影课:

public class Movie
{
    public string MovieName { get; set; }
}

控件以这种方式绑定:

dataControl.ItemsSource = Source;

2 个答案:

答案 0 :(得分:0)

您的代码现在就是这样,您告诉每个按钮都在其内部,并且水平对齐StackPanel。您需要包含一个水平StackPanel内的所有按钮。尝试做

<TextBlock Width="100" Height="50" FontSize="14" Text="{Binding Key}"></TextBlock>
<StackPanel Orientation="Horizontal">
    <ItemsControl Name="dataControl" ItemsSource="{Binding Value}">
         <ItemsControl.ItemTemplate>
              <DataTemplate>
                  <StackPanel Orientation="Horizontal">
                      <Button Content="{Binding MovieName}" Width="100" Height="100"/>                                        
                  </StackPanel>
              </DataTemplate>
         </ItemsControl.ItemTemplate>
     </ItemsControl>
</StackPanel>

答案 1 :(得分:0)

要水平对齐“电影海报”,您需要更改ItemsPanel,如下所示。

<ItemsControl Name="dataControl" ItemsSource="{Binding Value}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Content="{Binding MovieName}" Width="100" Height="100"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

ItemsPanel用于定义用于项目布局的面板。 ItemsControl的默认值为ItemsPanelTemplate,指定StackPanel。对于StackPanel,默认情况下Orientation设置为垂直。这就是你的物品垂直对齐的原因。

DataTemplate下的StackPanel控制每个项目内的布局,而不是ItemsControl内的项目布局。因此,将其Orientation设置为Horizontal将无效。由于每个项目只有一个Button,因此您只需注释掉StackPanel

相关问题