I made a simple game, where two players take turns. Sometimes, you can take 2 or more turns. Everything works fine, except I want to show how many turns each player did via binding.
I have page gamePage, class Game and Class Player:
page:
public partial class gamePage : Page
{
private Game game;
// konstruktor
public gamePage(string strPlayer1, string strPlayer2)
{
InitializeComponent();
Hrac player1= new Hrac(strPlayer1, 'R');
Hrac player2= new Hrac(strPlayer2, 'B');
this.game = new Game(player1, player2, width, height);
// binding
DataContext = game;
// etc...
}
// here is: mouse click - game.MakeAMove();
}
Game:
class Game : INotifyPropertyChanged
{
// binding
public event PropertyChangedEventHandler PropertyChanged;
// players
public Player player1;
public Player player2;
private Player activePlayer;
}
// konstruktor
public Game(Player player1, Player player2, int width, int height)
{
// init of players
this.player1 = player1;
this.player2 = player2;
this.activePlayer = player1;
}
public void MakeAMove()
{
activePlayer.Rounds++;
makeAChange("player1");
}
// binding - dle itNetwork
protected void makeAChange(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
Player:
class Player : INotifyPropertyChanged
{
// binding
public event PropertyChangedEventHandler PropertyChanged;
private int rounds;
public int Rounds {
get { return rounds; }
set
{
rounds = value;
// Call OnPropertyChanged whenever the property is updated
OnPropertyChanged("Rounds");
}
}
public char Color { get; set; }
public string Name { get; set; }
public Hrac(string name, char color)
{
this.Name = name;
this.Color = color;
Rounds = 0;
}
public override string ToString()
{
return this.Name;
}
// binding - via MSDN
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
XAML:
<TextBlock Name="tbPlayer1Rounds" Text="{Binding player1.Rounds}" />
Basicly players take turns, when they click, the move will happen and activePlayer will have one more turn (player1.Rounds), then players will swap and so on...
As you can see, I have tried a lots of things. First make a eventhandler in a game, then in a player itself. Made them public for sure. Nothing. The binding doesn't work. If I have property in Game called for example:int allRounds and in MakeAMove() I would increment that property + bind it to the textBlock, it works! But when I need to bind property in class which is in another class - I don't know what to do, I didn't find anything. Am I doing something wrong?
PS: Of course there is more code! It isn't that I don't want you to know what am I doing, it is just useless for binding and I don't want you to distract from the problem.
Edit: typos