获取位置已知的对象。我添加到我的网格

Get object with known pos. that I added to my grid

当我知道我之前添加到我的网格中的这个对象的确切位置(例如在第 1 行和第 2 列)时,我需要得到一个特定对象 Hall。 我有 class 调用 Seats,这个 class 存储关于矩形和一些方法的信息。为了更好地理解我在下面粘贴代码

class Seats
{
    Rectangle rec = new Rectangle();
    Grid hall;
    int row;
    int column;
    //some other stuff

    public Seats(Grid hall, int row, int column)
    {
        this.hall = hall;
        this.row = row;
        this.column = column;
        rec = new Rectangle();
        //some othe stuff
    }

    //some methods and func.
    
}


public MainWindow()
{
    InitializeComponent();
    Grid hall = new Grid();

    int rows, columns, r, c;

    Config(out rows, out columns) //ask user for num of rows and columns
    
    //this just show my grid
    for (r = 0; r < rows; r++)
    {
        hall.RowDefinitions.Add(new RowDefinition());
        for (c = 0; c < columns; c++)
        {
            if (row == 0)
        {
            hall.ColumnDefinitions.Add(new ColumnDefinition());
        }
            Seats seat = new Seats(hall, r, c);
        }
    }
}

public void GetSeat(Grid hall, int onRow, int onColumn)
{
    //here I need to get object seat which is for example on position: row 1 column 2 and change some of propreties
}

我认为 hall.GetValue(Grid.RowProperty, onRow), hall.GetValue(Grid.ColumnProperty, onColumn); 之类的东西可行。

与其将座位制作成网格,不如将它们制作成两个堆叠面板,一个包含每一行,每一行包含每个对象。所以像这样

<!-- main stackpanel containing rows of seats -->
<StackPanel Orientation="Vertical" Name="WhereTheSeatsAre">
    <!-- one row -->
    <StackPanel Orientation="Horizontal">
        <!-- one of the seats -->
        <Rectangle (!the seat's properties here!)/>
    </StackPanel>
</Stackpanel>

然后当您在“GetSeat()”函数中找到座位时:

// I took out the "grid hall" because it's not needed, at least the way that this is written
//if you need the paramater replace "WhereTheSeatsAre" with the paramater name, but it has to be a stackpanel
public void GetSeat(int onRow, int onColumn) {
    // get the row as a stackpanel
    StackPanel rowUI = WheretheSeatsAre.Children[onRow] as StackPanel;
    
    // get the seat from the row
    Rectangle seat = rowUI.Children[onCollumn] as Rectangle;
}

也看到了函数名,考虑这个,这将使它成为 return 席位,但它可能会成为一个实例:

public Rectangle GetSeat(int onRow, int onColumn) {
    // get the row as a stackpanel
    StackPanel rowUI = WheretheSeatsAre.Children[onRow] as StackPanel;
    
    // get the seat from the row
    Rectangle seat = rowUI.Children[onCollumn] as Rectangle;

    return seat;
}