数据绑定能应用于控件的任何属性。我看到过很多人提到能够绑定文本框的背景颜色到数据项,举个例子,超期的帐号的背景色显示红色。
但是如果你试图使用数据集或者数据表实现该功能,将会遇到问题。数据行只能保持受到限制的数据类型,并且不支持Color类型。如果你不能把颜色存储在数据中怎么能绑定颜色呢?
有些途径可以解决这个问题,但是最简单的是用绑定到自定义数据对象代替绑定到数据表。自定义业务对象的属性可能是Color型的,这样的属性能绑定到控件的BackColor属性。
为了演示,我定义了下面的自定义事务对象:
Public Class Account
Dim m_nAccountID As Integer
Dim m_sCustomerName As String
Dim m_dblBalance As Double
Public Sub New(ByVal nAccountID As Integer, ByVal sCustomerName As String, _ByVal dblBalance As Double)
Me.AccountID = nAccountID
Me.CustomerName = sCustomerName
Me.Balance = dblBalance
End Sub
Public Property AccountID() As Integer
Get
Return m_nAccountID
End Get
Set(ByVal Value As Integer)
m_nAccountID = Value
End Set
End Property
Public Property CustomerName() As String
Get
Return m_sCustomerName
End Get
Set(ByVal Value As String)
m_sCustomerName = Value
End Set
End Property
Public Property Balance() As Double
Get
Return m_dblBalance
End Get
Set(ByVal Value As Double)
m_dblBalance = Value
End Set
End Property
Public ReadOnly Property BackColor() As Color
Get
If m_dblBalance < 0 Then
Return Color.Salmon
Else
Return SystemColors.Window
End If
End Get
End Property
End Class
|
注意只读的BackColor属性从Balance属性中得到值,并且为负平衡(negative balance)暴露了一个不同的颜色。该类的其它元素很直接。
现在我们建立一个界面来操作这些对象的集合(见图5)。
图5.演示背景颜色绑定的窗体(设计时)
上面的三个文本框都用于保持当前Account对象的数据。它们分别叫txtAccountID、txtCustomerName和txtBalance.显示Load的按钮叫btnLoad,用于载入帐号集合。另两个按钮在记录间导航,分别叫btnBack 和 btnForward.
帐号对象集合可以保持在ArrayList(数组列表)中,因此下面一行代码应该在窗体代码的最前面:
Dim colAccounts As ArrayList
下面是Load方法的Click事件代码。它建立了一些Account对象并把它们放入一个集合中,接着把该集合绑定到文本框。
colAccounts = New ArrayList()
colAccounts.Add(New Account(1, "ABC Company", 10))
colAccounts.Add(New Account(2, "XYZ, Inc.", -10))
colAccounts.Add(New Account(3, "MNP Limited", 0))
txtAccountID.DataBindings.Add(New _
Binding("Text", colAccounts, "AccountID"))
txtCustomerName.DataBindings.Add(New _
Binding("Text", colAccounts, "CustomerName"))
txtBalance.DataBindings.Add(New _
Binding("Text", colAccounts, "Balance"))
txtBalance.DataBindings.Add(New _
Binding("BackColor", colAccounts, "BackColor")) 软件开发网 www.mscto.com
|
注意最后两行。txtBalance的Text属性绑定到一个帐号的Balance属性,并且该控件的BackColor属性绑定到帐号对象的BackColor属性。它演示了。NET框架组件绑定一个以上属性到不同数据项。
现在点击btnBack的Click事件,填入一下代码:
If Me.BindingContext(colAccounts).Position > 0 Then
Me.BindingContext(colAccounts).Position -= 1
End If
在btnForward的Click事件中写入以下代码:
If Me.BindingContext(colAccounts).Position < colAccounts.Count - 1 Then
Me.BindingContext(colAccounts).Position += 1
End If
|
启动项目并点击Load按钮。ABC公司的记录出现在文本框中。点击向前按钮,就是XYZ公司记录,同时,txtBalance的背景色变为橙红色(见图6)。
图6.数据绑定窗体显示了一个负平衡记录,引起Balance字段的背景色不同
过了该帐号记录后,该文本框的背景颜色将变回正常色。
Account类不是特别复杂。但是这个例子最少让你看到了怎样绑定不同属性(例如控件颜色)。