C# 在网格中重新定位子对象

C# 在网格中重新定位子对象,c#,wpf,windows,xaml,C#,Wpf,Windows,Xaml,我正试图用WPF实现一个C#国际象棋游戏。到现在为止,我可视化了国际象棋网格和其中的数字。我的.xaml文件只包含一个网格(名为“游乐场”),它是8x8。.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 :

我正试图用WPF实现一个C#国际象棋游戏。到现在为止,我可视化了国际象棋网格和其中的数字。我的.xaml文件只包含一个网格(名为“游乐场”),它是8x8。.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
    }
}
现在的问题是网格根本不做任何事情。我搜索了一些手动更新/重新绘制网格的方法,但没有找到任何结果。我还尝试先删除该子元素,然后再添加它,但这给了我一个错误,即该子元素已绑定到
UIElement
,我必须先将其分离。

你知道我做错了什么吗?

你需要更改
网格中原始
边框上的行和列

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

Grid.SetColumn(border, x);
Grid.SetRow(border, y);
但是,在
坐标
属性中,您正在设置
上的列和行

Grid.SetRow(this, (int)position.X); //relocate this (ChessTile)
Grid.SetColumn(this, (int)position.Y);
假设
这个
是您编写的自定义类,那么您需要确保它引用了原始的
边框
,并将
坐标设置器更改为:

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

请注意
=>
边框

的变化,即使有,尤其是没有,好的,您的问题也太广泛了。我建议:不要在代码隐藏中创建UI对象。一定要在两种不同的模型数据结构(如“视图模型”)中严格管理您的游戏状态,这两种模型数据结构代表游戏部件和棋盘位置。游戏棋子模型将具有棋盘位置和选择状态的属性。棋盘位置将具有基于第一次单击(选择棋子)和第二次单击(选择目的地)启用的单击命令,其中命令的启用状态相应地受到控制(即,在第一次单击之前,如果棋子位于该位置,则启用;在第一次单击之后,但在第二次单击之前,为所选棋子的有效移动位置启用)。如果UIElement在网格中,您所要做的就是更改该元素的grid.Row/grid.Column。我不确定会出什么问题,但就是这么简单。至少,您需要研究:MVVM、
ICommand
和数据模板。毫无疑问,在您看来,这比修复现有代码要麻烦得多现在。但我向您保证,从长远来看,它将显著提高您编写WPF代码的效率。@MichaelPuckettII:当然,这与在网格中移动项目有关。OP调试代码时遇到问题的最大原因是他将UI与非UI混合在一起。
Grid.SetRow(border, (int)position.X); //relocate the border!
Grid.SetColumn(border, (int)position.Y);