【发布时间】:2014-01-19 17:09:09
【问题描述】:
public class Game {
public Player Player1 {
get { return gameSettings.Player1; }
}
}
public class Player : INotifyPropertyChanged {
public int TotalScores {
get { return moves.Sum(move => move.ComposableWord.Length); }
}
public void AddMove(Move move) {
if (move == null)
throw new ArgumentNullException("move", "Move can not be null.");
moves.Add(move);
OnPropertyChanged("TotalScores");
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) {
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
在视图中
<StackPanel DataContext="{Binding Path=Game.Player1}">
<TextBlock Text="{Binding TotalScores}"/>
</StackPanel>
Caliburn 将 View 的 DataContext 设置为 GameBoardPageViewModel。
public class GameBoardPageViewModel {
public Game Game {
get { return game; }
}
}
我在调试器中看到,当调用 AddMove 时,没有人监听 PropertyChanged 事件(调用 AddMove 比 View 和 ViewModel 构造晚得多,因此必须在那时建立绑定)。
更新 1。 如果我调用 Game 属性的通知,则绑定有效。这种行为的原因是什么?
【问题讨论】:
-
你确定添加的Move的
ComposableWord属性的长度大于0吗? -
是的。绝对地。一切正常。如果我在 Game 属性上调用通知,则绑定有效。
-
game何时分配?绑定时是否可用?由于您没有通知它必须在那时可用,否则它将无法工作 -
@dkozl,哦,是的,确实,非常感谢。看来我累了)))你可以发布你的回复作为答案。
标签: wpf data-binding caliburn