您现在的位置: IT专家网 > WinSystem子站 > 技巧
让人迷恋 Avalon 数据绑定
作者: Chris Sells, 出处:微软, 责任编辑: 韩博颖,
2008-05-26 08:38
讨论 Avalon,并且将数据绑定引入其基于 Longhorn 的 Solitaire 应用程序。
我热爱我选择的生活方式,因为我花费一大部分时间来进行学习。当我学习新东西时,我从来不会对大脑中突然蹦出的“灵感”感到厌烦。最近我的大脑中就出现过这样一个灵感,它促使我从根本上重新考虑我编写用户界面的方法。下面是一个表明我原来做法的简单示例:
| class MyForm : Form { Game game1; StatusBar statusBar1; ... void InitializeComponent() { ... this.game1.ScoreChanged += new EventHandler(this.game1_ScoreChanged); ... } void game1_ScoreChanged(object sender, EventArgs e) { this.statusBar1.Text = "Score: " + this.game1.Score; } } |
绑定是要点所在
在 Windows 窗体中,我可以将此向前推进一步,即使用数据绑定将 Score 更改通知直接挂钩到状态栏控件:
| class MyForm : Form { Game game1; StatusBar statusBar1; ... public MyForm() { ... statusBar1.DataBindings.Add("Text", game1, "Score"); } ... } |
在该例中,由于 ScoreChanged 事件所使用的命名约定 (Changed),Windows 窗体可以及时注意到 Score 属性的更改并直接设置状态栏控件的 Text 属性。然而,该方案中缺少的是将数据与“Score:”前缀进行合成的机会。要获得该功能,我们必须处理 Binding 对象上的 Format 事件,该事件是通过调用 DataBindings 集合的 Add 方法创建的:
| public MyForm() { ... Binding binding = statusBar1.DataBindings.Add("Text", game1, "Score"); binding.Format += new ConvertEventHandler(binding_Format); } void binding_Format(object sender, ConvertEventArgs e) { e.Value = "Score: " + e.Value.ToString(); } |
- 本文关键词:

