将孩子重新安置在网格中

时间:2017-04-30 20:43:46

标签: c# wpf windows xaml

我正在尝试使用WPF在C#中实现国际象棋游戏。到现在为止,我想象出国际象棋网格及其中的数字。我的.xaml文件只包含一个8x8的网格(名为“playground”)。 .xaml.cs文件中的初始化如下所示:

for (int x = 0; x < 8; x++)
{
    for (int y = 0; y < 8; y++)
    {
        Border border = new Border();

        if (y % 2 == (x % 2 == 0 ? 0 : 1))
        {   // Chess like look
            border.Background = black; //black is a static SolidColorBrush
        }

        // a ChessTile is an Image which can be a Figure or an EmptyTile
        // omitted code... evaluate whether what figure the tile is or empty
        ChessTile tile;

        Grid.SetColumn(border, x);
        Grid.SetRow(border, y);

        border.HorizontalAlignment = HorizontalAlignment.Stretch;
        border.VerticalAlignment = VerticalAlignment.Stretch;

        if (tile is Figure)
        {
            // Set Event to border so the user is able to click outside the image
            border.MouseDown += ClickFigure; 
        }

        border.Child = tile; // Set tile as Child
        playground.Children.Add(border); // Add border to Child
    }
}

初始化后,我想将国际象棋棋子移动到网格中的另一列和/或行。目前我在ClickFigure中评估图形能够移动到哪个空图块,然后向这些空图块添加一个新的处理程序并在那里移动我的图形。我在处理程序中调用tile.Move(otherTile):
(来自ChessTile.cs)

public Vector Coordinates
{
    get
    {
        return position; //private Vector
    }
    private set
    {
        position = value;
        Grid.SetRow(this, (int)position.X); //relocate this (ChessTile)
        Grid.SetColumn(this, (int)position.Y);
    }
}

public void Move(ChessTile other)
{
    Vector temp = position;
    Coordinates = other.position; //relocating both tiles through properties
    other.Coordinates = temp;
}

现在的问题是网格根本不做任何事情。我搜索了一些方法来手动更新/重绘网格,但我没有找到任何东西。我还尝试先移除孩子,然后再次添加它,但这给了我一个错误,说孩子已经绑定到UIElement并且我必须先将其分开。
你知道我做错了什么吗?

1 个答案:

答案 0 :(得分:0)

您需要更改位于Border内的原始Grid上的行和列。

在您的设置代码中,您可以在边框对象上设置列和行:

Grid.SetColumn(border, x);
Grid.SetRow(border, y);

但是在Coordinates媒体资源中,您需要在this上设置列和行。

Grid.SetRow(this, (int)position.X); //relocate this (ChessTile)
Grid.SetColumn(this, (int)position.Y);

假设this是您编写的自定义类,那么您需要确保它具有对原始Border的引用,并将您的Coordinate setter更改为:< / p>

Grid.SetRow(border, (int)position.X); //relocate the border!
Grid.SetColumn(border, (int)position.Y);

请注意this =&gt;的更改border

相关问题