WPF - 彼此相邻的按钮

时间:2016-08-08 07:24:41

标签: wpf

我有按钮,在他下面是文字,这些按钮彼此相邻但在他下面服务。这是我的代码:  UserView.xaml:

<WrapPanel Orientation="Horizontal" HorizontalAlignment = "Left">
        <ItemsControl ItemsSource = "{Binding Path = Users}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation = "Vertical">
                        <Button Style="{StaticResource UserButton}" Content="{Binding Name}"></Button>
                        <Rectangle Style="{StaticResource UserButtonStatus}" 
                                       Fill="{Binding Color}" ToolTip="{Binding Tooltip}"/>
                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </WrapPanel>

MainWindow.xaml:

 <StackPanel Grid.Row="0" Grid.Column="0" Orientation="Vertical">
            <TextBlock Style="{StaticResource Title}">Users</TextBlock>
            <view:UserView x:Name="UserView">
                <view:UserView.DataContext>
                    <Binding Path="UserViewModel" Source="{StaticResource ServiceLocator}"/>
                </view:UserView.DataContext>
            </view:UserView>
        </StackPanel>

必需:

enter image description here

实际(错误):

enter image description here

1 个答案:

答案 0 :(得分:3)

您需要覆盖项目控制面板

项目控件默认会显示彼此之下的每个项目。

这里是要添加的代码,请确保它在项目控件标签中,就像您使用项目模板一样:

<ItemsControl.ItemsPanel>
     <ItemsPanelTemplate>
           <WrapPanel/>
     </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>

所以你的userview.xaml将如下所示:

<ItemsControl ItemsSource = "{Binding Path = Users}">

     <ItemsControl.ItemsPanel>
          <ItemsPanelTemplate>
              <WrapPanel/>
          </ItemsPanelTemplate>
     </ItemsControl.ItemsPanel>

     <ItemsControl.ItemTemplate>
          <DataTemplate>
               <StackPanel Orientation = "Vertical">
                    <Button Style="{StaticResource UserButton}" Content="{Binding Name}"></Button>
                    <Rectangle Style="{StaticResource UserButtonStatus}" Fill="{Binding Color}" ToolTip="{Binding Tooltip}"/>
               </StackPanel>
          </DataTemplate>
     </ItemsControl.ItemTemplate>
</ItemsControl>