【发布时间】:2017-01-26 12:18:46
【问题描述】:
我做了一个简单的游戏,两个玩家轮流玩。有时,您可以转 2 圈或更多圈。一切正常,除了我想显示每个玩家通过绑定完成了多少回合。
我有page gamePage、class Game和Class Player:
页面:
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();
}
游戏:
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));
}
玩家:
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}" />
基本上玩家是轮流的,当他们点击时,会发生移动,并且activePlayer会多回合(player1.Rounds),然后玩家会交换等等......
如您所见,我已经尝试了很多东西。首先在游戏中制作事件处理程序,然后在玩家本身中制作。肯定让他们公开。没有。绑定不起作用。如果我在游戏中有属性,例如:int allRounds 和MakeAMove(),我会增加该属性并将其绑定到 textBlock,它可以工作!但是当我需要在另一个类中绑定属性时 - 我不知道该怎么做,我什么也没找到。我做错了吗?
PS:当然还有更多代码!不是我不想让你知道我在做什么,只是对绑定没用,我不想让你分心。
编辑:错别字
【问题讨论】:
标签: c# wpf data-binding