【发布时间】:2011-11-28 12:13:15
【问题描述】:
我想将 TextBlocks 绑定到 Modell。但它不起作用,我不知道为什么。
class GameModel : INotifyPropertyChanged {
string[] _teamNames;
...
public string teamName(int team)
{
return _teamNames[team];
}
public void setTeamName(int team, string name)
{
_teamNames[team] = name;
OnPropertyChanged("teamName");
}
protected void OnPropertyChanged(string name) {
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
以及创建文本框的代码
for (int currCol = 0; currCol < teams; currCol++) {
TextBlock teamNameBlock = new TextBlock();
Binding myNameBinding = new Binding();
myNameBinding.Source = myGame;
myNameBinding.Path = new PropertyPath("teamName", currCol);
myNameBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
teamNameBlock.SetBinding(TextBlock.TextProperty, myNameBinding); //The name of the team bind to the TextBlock
...
}
【问题讨论】:
-
这可能不是唯一的问题,但您的 teamName 函数不是属性。您应该查看有关“索引属性”的文档
-
有没有可能绑定一个函数结果?
-
不,你必须绑定到一个属性,但你可以在属性的“get{}”中调用一个函数
-
实际上可以使用转换器绑定到方法。示例见stackoverflow.com/questions/502250/bind-to-a-method-in-wpf