【发布时间】:2014-02-22 10:09:50
【问题描述】:
我正在使用 WPF 和 C# 开发一个迷宫,我将代理放置在迷宫内的随机位置,GUI 显示使用搜索算法找到出口的过程。
我首先将网格划分为行和列,然后在每个网格/行对上添加一个矩形,最后在代表我的代理的网格中添加一个额外的矩形。
我想将代理 Rectangle 在 Grid 中的位置绑定到代理类属性,该属性用 Point 类表示其位置。
由于我对这些技术还很陌生,所以我在网上查看并提供了当前的解决方案:
创建一个新的矩形类,我称之为 ExtendedRectangle,并在其中创建一个自定义 DependencyProperty,让我可以通过 Point 控制 Grid.RowProperty 和 Grid.ColumnProperty。
问题是调试代码并在我的 setter 和 getter 上设置断点,似乎在使用 setValue() 方法执行期间没有达到断点,但是当我显式修改其值时它们被调用。此外,我在运行时更改了 Agents 矩形的位置,我看到值正在更新,但我的 GUI 没有。
我想对此或更好的方法有所启发。谢谢。
这就是我在 MainWindow.xaml.cs 上进行绑定的方式:
public partial class MainWindow : Window
{
Maze maze = new Maze(15, 15);
TimerCallback callback; //
Timer stateTimer; //
public MainWindow()
{
InitializeComponent();
DataContext = maze;
DrawMap(15, 15);
callback = new TimerCallback(Update); //
stateTimer = new Timer(callback, null, 2000, 2000); //
}
public void DrawMap(int ancho, int alto)
{
/********ADD COLUMNS, ROWS AND RECTANGLES CODE WAS HERE*************/
// commented code are my tests
ExtendedRectangle agent = new ExtendedRectangle();
agent.BaseRectangle.Fill = new SolidColorBrush(Colors.LightGreen);
//agent.GridPosition = new Point(5, 5);
//Console.WriteLine(agent.GridPosition.ToString());
//Console.WriteLine(maze.GetAgent().Position.ToString());
agent.SetValue(ExtendedRectangle.GridPositionProperty, maze.GetAgent().Position);
//Console.WriteLine(agent.GridPosition.ToString());
Binding bind = new Binding("Position") { Source = maze.GetAgent() };
bind.Mode = BindingMode.OneWay;
//bind.Converter = new AgentToGridPosition();
agent.SetBinding(ExtendedRectangle.GridPositionProperty, bind);
Mapa.Children.Add(agent.BaseRectangle);
}
public void Update(Object stateInfo) //
{
Random r = new Random();
int x = r.Next(0, 14);
int y = r.Next(0, 14);
Point p = new Point(x, y);
maze.GetAgent().Position = p;
Console.WriteLine("UPDATED POSITION:" + maze.GetAgent().Position.ToString());
}
}
这是我的 ExtendedRectangle 类:
class ExtendedRectangle
{
private Rectangle baseRectangle;
private Point propertyType;
public ExtendedRectangle()
{
baseRectangle = new Rectangle();
propertyType = new Point();
}
public Rectangle BaseRectangle
{
get
{
return baseRectangle;
}
}
public static readonly DependencyProperty GridPositionProperty = DependencyProperty.Register(
"GridPosition", typeof(Point), typeof(ExtendedRectangle));
public Point GridPosition
{
get
{
propertyType.X = Convert.ToDouble(baseRectangle.GetValue(Grid.ColumnProperty));
propertyType.Y = Convert.ToDouble(baseRectangle.GetValue(Grid.RowProperty));
return propertyType;
}
set
{
propertyType = value;
baseRectangle.SetValue(Grid.ColumnProperty, (int)propertyType.X);
baseRectangle.SetValue(Grid.RowProperty, (int)propertyType.Y);
}
}
public void SetValue(DependencyProperty dp, object value)
{
baseRectangle.SetValue(dp, value);
}
public BindingExpressionBase SetBinding(DependencyProperty dp, BindingBase binding)
{
return baseRectangle.SetBinding(dp, binding);
}
}
【问题讨论】:
标签: c# wpf data-binding