我正在使用 WPF 和 C#,并且我有一个 Canvas ,上面有矩形(就像迷宫一样)。现在我想创建一个在这个迷宫中移动(在算法的帮助下)的角色。因此,我创建了一个名为“字符”的新类,但我的问题从这里开始:如何在 Canvas 上创建一个具有图像、位置并且可以访问字符类中的方法和属性的对象? 所以最终的结果应该是这样的:
private class MainWindow
{
//Here the canvas is made visible and the rectangles are being drawn on the canvas
//Then a method should start to create the character and move him through the maze
//it should look like (character.move(1) so the character moves one step forward etc.)
}
private class Character
{
//here are the methods and attributes the character should have
}
提前致谢,并对我的英语不好表示歉意:)
最佳答案
如果从相反的方向看问题,解决起来就容易多了。
创建您的角色对象,将其连接起来,以便数据(模型)中的一切按照您的预期运行。然后,您需要添加表示角色位置的属性,例如
public int XCoordinate { get; set; }
public int YCoordinate { get; set; }
确保移动在模型端完成。。如果您尝试根据视觉显示来驱动运动,则会使程序变得过于复杂。
接下来,定义 Canvas 中角色的 View ,如下所示:
<Canvas ...>
<Image Canvas.Left="{Binding XCoordinate}" Canvas.Top="{Binding YCoordinate}" .../>
</Canvas>
最后,确保您的绑定(bind)语法正确(您是否设置了 DataContext?),并确保设置了 NotifyPropertyChanged(这两个内容在其他地方都有详细介绍)。然后,您将设置一个整齐划分的模型和 View ,并且应该更容易专注于运动逻辑或您想要的任何其他内容。
关于c# - WPF Canvas 创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13202661/