1

I'm learning to create WPF applications and I got a homework. I have to create a wpf mvvm "tron lightcycle game", but unfortunately got stuck.

In the View (Mainwindow.xaml) there is a Canvas. I should draw here.

...    
<Canvas Name="cnvs_game" Margin="5,5,5,5">
...

In the ViewModel there is a GameData class and a Timer. Every tick the GameData updates(GameTime,Player1CanvasPosition (Point),... ).

I bid the Gametime to the View like this:

Mainwindow.xaml.cs:

...
<TextBlock Text="{Binding GameTime}" />
...

ViewModel.cs:

...
private GameData _GameData;
...
public String GameTime { get { return _GameData.GameTime.ToString(); } }
...

private void GameTimer_Tick(object sender, EventArgs e)
{
    _GameData.Step();
    OnPropertyChanged("GameTime"); // PropertyChanged with error handling
    OnPropertyChanged("Player1CanvasPosition ");
    OnPropertyChanged("Player2CanvasPosition ");
}

The GameTime refresh in the View. It wasn't hard. But I still have no idea how to draw.

How should I get the Player1CanvasPosition and draw there a Rectangle (in the Canvas). What is the best way to do this? Help Me Please! :S

BlackCat
  • 521
  • 3
  • 8
  • 22

1 Answers1

2

You can do this the same way you did With the GameTime, for example:

<Canvas Name="cnvs_game" Margin="5,5,5,5">
    <Rectangle Canvas.Left="{Binding Player1CanvasPositionX}" Canvas.Top="{Binding Player1CanvasPositionY}" ... />
    <Rectangle Canvas.Left="{Binding Player2CanvasPositionX}" Canvas.Top="{Binding Player2CanvasPositionY}" ... />
 ...

And create the Player1CanvasPositionX property in the ViewModel which call the OnPropertyChanged, then when changing the properties in the ViewModel the rectangles will move.

Edit: For dynamically adding rectangles I would use an ItemsControl which is bound to an ObservableCollection of positions. The ItemsControl datatemplate would contain a rectangle which would bind to the position. Look at this link for more details WPF Canvas, how to add children dynamically with MVVM code behind.

Community
  • 1
  • 1
sam1589914
  • 806
  • 4
  • 9
  • Thank you very much for your answer. Yes this is my thought too, but the problem is that I have to draw a the line(s), and do not only to move the motor. I should put a new rectangle every time when the position changes. – BlackCat Dec 04 '12 at 09:00
  • I updated with some more info which might be helpful for you! – sam1589914 Dec 04 '12 at 09:25
  • Ah, thank you very much. I think I will be able to do it now. – BlackCat Dec 04 '12 at 09:33