如何将数据模板项格式化为类似表格的外观

本文关键字:表格 外观 格式化 数据 | 更新日期: 2023-09-27 18:20:05

我正在尝试将动态创建的数据模板项(绑定到对象)显示为表格式。我的堆叠面板和包裹面板都不会像我最初使用按钮时那样格式化。我相信我的面板控件实际上并没有格式化其中的项目。

以下是我的代码的几个相关示例:

主窗口后面的代码c#

int numTapeSlots = 16;
public ObservableCollection<Tape> topTapes;
    public MainWindow()
    {
        InitializeComponent();
        topTapes = new ObservableCollection<Tape>();           
        topTapeSlots.ItemsSource = topTapes;            
        //Create Buttons Top Tray
        for (int i = 1; i <= (numTapeSlots / 2); i++)
        {
            topTapes.Add(new Tape(i));
        }
     }

xaml

<Window.Resources>
  <DataTemplate x:Key="TapeSlot">
    <Border  MouseUp="Border_MouseUp"
             BorderBrush="Black"
             BorderThickness="5">
      <Grid>
        <TextBlock x:Name="slotLocation"
                   Text="{Binding Path=tapeLocation}"
                   Height="25"
                   Width="30" />
      </Grid>
    </Border>
  </DataTemplate>
</Window.Resources>
<WrapPanel x:Name="wpTopTray"
           Grid.Column="1"
           Margin="20,20,20,20"
           VerticalAlignment="Top">
  <ItemsControl Name="topTapeSlots"
                ItemTemplate="{StaticResource TapeSlot}" />
</WrapPanel>

注意:WrapPanel与按钮配合使用效果良好

现在的情况是,对象垂直显示在一条直线上。它几乎忽略了wrapPanel控件属性。

如何将数据模板项格式化为类似表格的外观

您应该使用ItemsPanel:

        <ItemsControl Name="topTapeSlots" ItemTemplate="{StaticResource TapeSlot}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>