C# 将子项附加到网格,设置它的行和列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11701749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:53:41  来源:igfitidea点击:

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

c#wpfxamlgridview

提问by Novak

How can I append an Imageobject into a Gridand set it's Rowand Column?

如何将Image对象附加到 aGrid并将其设置为RowColumn

The grid is 3x3.

网格是 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);
          }
     }
}

采纳答案by Gerard Sexton

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

Grid setter 方法是静态的。
将它们放在第 1 行第 1 列中:

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

回答by Rohit Agrawal

You can use following to set for any UIElement

您可以使用以下设置为任何 UIElement

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

回答by yo chauhan

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.

是的,网格是 4X3 而非 3X3 尺寸。我希望这将有所帮助。

回答by klm_

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);
      }
 }
}