【问题标题】:UserControls stack vertically instead of horizontal [duplicate]UserControls垂直堆叠而不是水平堆叠[重复]
【发布时间】:2019-04-04 12:46:15
【问题描述】:

我的用户控件被加载了 X 次,并且应该彼此并排加载,直到没有空间为止。我试过使用包装面板,但这没有区别,也没有水平堆栈面板。我显然在这里做错了,希望得到建议:

XAML 页面:

<Grid Background="#FFFFFF">        
    <Grid.RowDefinitions>
        <RowDefinition Height="auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Label Grid.Row="0" x:Name="lblCellPageTitle" Content="Cellect" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" HorizontalAlignment="Center" Height="43"  VerticalAlignment="Top" Width="221" FontSize="22"/>
    <StackPanel Grid.Row="1" Orientation="Horizontal">
        <ItemsControl Grid.Row="1" Name="CellControlContainer"/>
    </StackPanel>
</Grid>

用户控制按钮:

<UserControl x:Class="WpfApp1.UserControls.CellButton"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WpfApp1"
             mc:Ignorable="d" 
             d:DesignHeight="100" d:DesignWidth="180">

        <Button Name="Cellx" Content="CellX" Width="100" Height="100" FontSize="19" Padding="5" Click="Cellx_Click"  />

</UserControl>

Page.cs(调用用户控件):

 public partial class CellNumber : Page
    {

        public CellNumber()
        {
            InitializeComponent();

            for (int i = 0; i <= Global.noCells; i++)
            {
                CellControlContainer.Items.Add(new UserControls.CellButton(i));
            }
        }
  • 当前结果 - 按钮垂直堆叠
  • 期望的结果 - 按钮被水平包裹

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    使用水平 WrapPanel 或 StackPanel 作为 ItemsControl 的ItemsPanel

    <ItemsControl Name="CellControlContainer">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel Orientation="Horizontal"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>
    

    除此之外,与其在代码中添加项目,不如更好地将ItemsSource 属性分配或绑定到数据项的(可选可观察的)集合,并通过用作ItemsControl 的ItemTemplate 的DataTemplate 创建它们的可视化表示就像这个简单的例子:

    <ItemsControl ItemsSource="{Binding CellRange}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel Orientation="Horizontal"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <usercontrol:CellButton Number="{Binding}" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
    

    【讨论】: