2013-09-05 72 views
0

我在ItemTemplate上有一個帶Label1和Button1的DataRepeater1。這三個控件綁定到BindingList(Of T),其中T是atm,它是一個非常簡單的類,它具有單個字符串屬性更改綁定數據時DataRepeater不會更新

當用戶單擊其中一個DataRepeater Item按鈕時,它將更新綁定數據中的字符串名單。 I.E.如果用戶單擊DataRepeater中的項0上的按鈕,則相同索引的BindingList中的字符串將發生更改。

這工作

什麼不工作是字符串改變的DataRepeater因爲它綁定到該字符串應該更新的Label1爲相關項目後續 - 但事實並非如此。

誰能告訴我爲什麼?我目前的代碼如下。由於

Imports System.ComponentModel 

Public Class Form1 
    Class ListType 
     Public Sub New(newString As String) 
      Me.MyString = newString 
     End Sub 
     Public Property MyString As String 
    End Class 
    Dim MyList As New BindingList(Of ListType) 

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 
     ' Bind BindingList to DataRepeater. 
     Label1.DataBindings.Add("Text", MyList, "MyString") 
     DataRepeater1.DataSource = MyList 

     ' Add some items to the BindingList. 
     MyList.Add(New ListType("First")) 
     MyList.Add(New ListType("Second")) 
     MyList.Add(New ListType("Third")) 
    End Sub 

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
     ' Use the Index of the current item to change the string 
     ' of the list item with the same index. 
     MyList(DataRepeater1.CurrentItemIndex).MyString = "Clicked" 

     ' Show all the current list strings in a label outside of 
     ' the DataRepeater. 
     Label2.Text = String.Empty 
     For Each Item As ListType In MyList 
      Label2.Text = Label2.Text & vbNewLine & Item.MyString 
     Next 
    End Sub 
End Class 

回答

0

嗯,這似乎有些奇怪,但是經過進一步的實驗,我發現,而不是關注指數等於複製在直接更改字符串,創建對象的副本,改變字符串,使物體作品。

如:

Dim changing As ListType = MyList(DataRepeater1.CurrentItemIndex) 
    changing.MyString = "Clicked" 
    MyList(DataRepeater1.CurrentItemIndex) = changing 

或者更短的版本:

MyList(DataRepeater1.CurrentItemIndex).MyString = "Clicked" 
    MyList(DataRepeater1.CurrentItemIndex) = MyList(DataRepeater1.CurrentItemIndex) 

似乎是莫名其妙的BindingList只通知DataRepeter當整個對象的變化,而不是對象的成員...

1

看看INotifyPropertyChanged

INotifyPropertyChanged接口用於通知客戶端(通常爲綁定客戶端)屬性值已更改。

它使用這種機制,BindingList類能夠將單個對象的更新推送到DataRepeater

如果要實現TINotifyPropertyChanged接口方面,BindingList將被通知的任何變化T並將它們轉發到DataRepeater你。每當屬性發生變化時(在T的屬性的設置者中),您只需提升PropertyChanged事件。

有關使用此方法的.NET Framework文檔有walkthrough。 「

+1

」雖然此鏈接可能回答問題,但最好在此處包含答案的重要部分並提供參考鏈接。如果鏈接頁面更改爲「 – zero323

+1

@ zero323:I'已經更新瞭解釋如何使用INotifyPropertyChnaged的答案。謝謝。 –

相關問題