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