C# WPF中带有多个项目的统一网格控件

3
我需要一个像下面这样的窗口:

enter image description here

我尝试实现这个功能,但没有得到完美的结果。我哪里做错了?
    <UniformGrid>
    <ItemsControl ItemsSource="{Binding Data}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
           <Border  BorderBrush="Black" Background="Gainsboro" BorderThickness="3" Margin="2" Width="100" >  
              <Grid FlowDirection="LeftToRight">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                </Grid.RowDefinitions>

                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>

                <Label HorizontalAlignment="Center" Content="{Binding Label1Text}" Grid.Row="1" Margin="2"/>

                <Label HorizontalAlignment="Center" Content="{Binding Label2Text}" Grid.Row="2" Margin="2"/>

                <Button HorizontalAlignment="Center" Content="Button1" Width="80" Height="80"
                        Command="{Binding DataContext.Command1, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
                        CommandParameter="{Binding}"
                        Grid.Row="0"  Margin="2"/>
            </Grid>
        </Border>

        </DataTemplate>
        </ItemsControl.ItemTemplate>

        <ItemsControl.Template>
            <ControlTemplate TargetType="ItemsControl">
                <ScrollViewer CanContentScroll="True">
                    <ItemsPresenter/>
                </ScrollViewer>
            </ControlTemplate>
    </ItemsControl.Template>

   </ItemsControl>
  </UniformGrid>

结果窗口;

描述图片

2个回答

3
尝试将ItemsPanel模板更改为UniformGrid,而不是将ItemsControl包裹在UniformGrid中。您还可以尝试使用WrapPanel而不是UniformGrid
.......
<ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
                <UniformGrid Columns="2"/>
                <!--  <WrapPanel/> -->
        </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
.......

我没听懂你的意思,我需要把“<ItemsControl.ItemTemplate>”改成“<ItemsControl.ItemsPanel>”吗? - iJay
我的意思是,除了你已经有的<ItemsControl.ItemTemplate>之外,尝试将<ItemsControl.ItemsPanel>设置为上面所述。 - har07
WrapPanel不允许您设置列数。 - imekon

0

您需要指定列数:

<UniformGrid Columns="2">
....

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接