Append a child to a grid, set it's row and column

左心房为你撑大大i 提交于 2019-12-21 06:52:21

问题


How can I append an Image object into a Grid and set it's Row and Column?

The grid is 3x3.

Main file:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="440" Width="400" ResizeMode="NoResize">
    <Window.Background>
        <ImageBrush ImageSource="C:\Users\GuyD\AppData\Local\Temporary Projects\WpfApplication1\AppResources\Background.png"></ImageBrush>
    </Window.Background>
    <Grid ShowGridLines="True" x:Name="myGrid">
        <Grid.RowDefinitions>
            <RowDefinition Height="42" />
            <RowDefinition Height="30*" />
            <RowDefinition Height="30*" />
            <RowDefinition Height="32*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="31*" />
            <ColumnDefinition Width="26*" />
            <ColumnDefinition Width="32*" />
        </Grid.ColumnDefinitions>
    </Grid>
</Window>

Code behind file:

public MainWindow()
{
     InitializeComponent();
     for (int i = 0; i < 3; i++)
     {
          for (int j = 0; j < 3; j++)
          {
               Image Box = new Image();
               this.myGrid.Children.Add(Box);
          }
     }
}

回答1:


The Grid setter methods are static.
To place them in row 1 column 1:

Image Box = new Image();
myGrid.Children.Add(Box);
Grid.SetRow(Box, 1);
Grid.SetColumn(Box, 1);



回答2:


You can use following to set for any UIElement

Grid.SetRow(Box, i);
Grid.SetColumn(Box, j);



回答3:


for (int i = 0; i < 4; i++)
      {
        for (int j = 0; j < 3; j++)
        {
           Image Box = new Image();
           this.myGrid.Children.Add(Box);
           Grid.SetRow(Box, i);
           Grid.SetColumn(Box, j);
        }
     }

And yes the Grid is of 4X3 not of 3X3 dimensions. I hope this will help.




回答4:


Try this:

public MainWindow() {
 InitializeComponent();
 for (int i = 0; i < 3; i++)
 {
      for (int j = 0; j < 3; j++)
      {
           Image Box = new Image();
           Grid.SetRow(Box, i);
           Grid.SetColumn(Box, j);
      }
 }
}


来源:https://stackoverflow.com/questions/11701749/append-a-child-to-a-grid-set-its-row-and-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!