VB.NET數(shù)據(jù)綁定應(yīng)用技巧講解
VB.NET編程語言的推出為開發(fā)者又增加了一種語言的選擇。他們可以利用這一款語言實現(xiàn)各種特定的功能。VB.NET數(shù)據(jù)綁定能應(yīng)用于控件的任何屬性。我看到過很多人提到能夠綁定文本框的背景顏色到數(shù)據(jù)項,舉個例子,超期的帳號的背景色顯示紅色。
但是如果你試圖使用數(shù)據(jù)集或者數(shù)據(jù)表實現(xiàn)該功能,將會遇到問題。數(shù)據(jù)行只能保持受到限制的數(shù)據(jù)類型,并且不支持Color類型。如果你不能把顏色存儲在數(shù)據(jù)中怎么能綁定顏色呢?
有些途徑可以解決這個問題,但是最簡單的是用VB.NET數(shù)據(jù)綁定到自定義數(shù)據(jù)對象代替綁定到數(shù)據(jù)表。自定義業(yè)務(wù)對象的屬性可能是Color型的,這樣的屬性能綁定到控件的BackColor屬性。
為了演示,我定義了下面的自定義事務(wù)對象:
- 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屬性中得到值,并且為負(fù)平衡(negative balance)暴露了一個不同的顏色。該類的其它元素很直接。
VB.NET數(shù)據(jù)綁定的相關(guān)應(yīng)用技巧就為大家介紹到這里。
【編輯推薦】