动态创建的Binding不起作用
我想将 TextBlock 绑定到 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
...
}
I want to bind TextBlocks to a Modell. But it does not work and I have no idea why.
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));
}
}
And the code which creates the TextBoxes
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
...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个完整的、有效的示例。这个想法是使用索引属性来访问团队名称。
请注意如何创建绑定路径:PropertyPath("[" + currCol + "]") ,以及如何通知属性更改:OnPropertyChanged("Item[]");
创建控件后,将第三组的名称更改为“Marge”以测试绑定。
Here's a full, working example. The idea is to use an indexed property to access the team names.
Note how the binding path is created: PropertyPath("[" + currCol + "]") , and how the property change is notified: OnPropertyChanged("Item[]");
After the creation of controls, the name of the 3rd team is changed to "Marge" to test the binding.
我认为问题是您绑定到
什么是“team”参数以及更改的时刻?谁设置该参数。
相反,请进行如下操作:
您绑定到一个属性,该属性根据
currTeam
索引返回团队名称,该索引是根据您的应用程序逻辑设置的。希望这有帮助。
I think the problem is you bind to
what is
team
parameter and the moment of change? Who sets that parameter.Make something like this, instead:
You bind to a property, which returns the team name based on
currTeam
index, which is settuped based on you app logic.Hope this helps.