在代码后面插入图像到网格

本文关键字:图像 网格 插入 代码 | 更新日期: 2023-09-27 18:12:50

我找到了很多关于如何在XAML文件中手动添加东西到网格的教程,但是我正在制作的网格是一个15x15的怪物,需要插入100多个图像。我希望有一些访问器允许我使用循环在代码隐藏文件中添加图像。

<Grid Name="ScrabbleBoard">
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
</Grid>

在代码后面插入图像到网格

您需要使用Grid::Children属性来添加图像元素。然后使用Grid设置元素的行和列。SetRow(element, rowIndex)/element. setvalue (Grid. setvalue)RowProperty, rowIndex)和Grid。SetColumn(element, columnIndex)/element. setvalue (ColumnProperty columnIndex)

for (int rowIndex = 0; rowIndex < ScrabbleBoard.RowDefinitions.Count; rowIndex++)
{
    for (int columnIndex = 0; columnIndex < ScrabbleBoard.ColumnDefinitions.Count; columnIndex++)
    {
        var imageSource = new BitmapImage(new Uri("pack://application:,,,/YourProjectName;component/YourImagesFolderName/YourImageName.jpg"));
        var image = new Image { Source = imageSource };
        Grid.SetRow(image, rowIndex);
        Grid.SetColumn(image, columnIndex);
        ScrabbleBoard.Children.Add(image);
    }
}

既然你没有跨越或控制宽度/高度,那么使用统一的网格控件会更简单。这会将子单元格添加到下一个单元格中,因此可以通过对图像集合执行foreach循环来完成。