在 C# 的网格中插入对象

Insert objects inside a Grid from c#

我在 xaml 代码中有一个包含一些行和列的网格。在 c# 代码中,我有一个列表,我希望其中包含的每个对象都位于网格的特定点。例如:对象 1:第 1 列第 1 行,对象 2:第 2 列第 1 行等。我该怎么办?

<Grid Margin="15">
                <Grid.RowDefinitions>
                    <RowDefinition Height="40"/>
                    <RowDefinition Height="50"/>
                    <RowDefinition Height="2"/>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
</Grid>

列表中包含一些对象

ObservableCollection<HumorDiary> listDiario = new ObservableCollection<HumorDiary>();

列表中的项目可能会有所不同,它们没有预先确定的数量。 对于列表中的每个元素,我想在 Grid

中创建一个按钮

Grid 有一个 Children 集合

myGrid.Children.Add(myElement, col, row);

你应该使用 ItemsControl,它有四个部分:

  • 您将 collection 绑定到 ItemsSource 属性。
  • 您定义项目模板,它决定模型项目 (HumorDiary) 在屏幕上的显示方式。
  • 您定义面板模板,它定义了您的项目如何组合在一起。在这种情况下,这将是您在上面定义的 Grid
  • 要将这些东西放置在您的网格中,您需要设置项目模板的样式并将 Grid.RowGrid.Column 属性绑定到定义它们应添加到何处的属性。