2012-02-20 25 views
0

我已經有這個東西在另一個項目中工作,但現在沒有。 我不知道爲什麼。DataGrid沒有更新來自List(of)對象的行

  1. 設置的DataGrid的ItemsSource到{Binding}
  2. 創建新的目錄
  3. (的MyClass的)創建公共列表Dim MyList As New List(of myclass)
  4. 綁定DataGrid.DataContext = MyList當實例被創建
  5. 設置DataGrid列的定義對MyClass的一些項目屬性

我在列表中添加了我的第一堂課 MyList.Add(New myclass()) 現在,該項目可見。但是在創建實例並在數據網格可見之後,這些行不會更新。 MyList.Add(New myclass())並且沒有第二行可見。

只有在做 MyDataGrid1.Items.Refresh 項目更新正確。 但據我所知,List(of)類已經包含了INotifyPropertyChanged接口。

任何想法爲什麼會失敗?

這裏一些額外的代碼

 <DataGrid.Columns> 
      <DataGridTextColumn   Header="N°"     Binding="{Binding Path=LineNumber, StringFormat='{}{0:000}'}"   Width="SizeToCells"  MinWidth="30" IsReadOnly="True" /> 

      <DataGridTextColumn   Header="HEX"    Binding="{Binding HexText}"   Width="SizeToHeader" MinWidth="80" IsReadOnly="True" FontWeight="Bold"     /> 
      <DataGridTextColumn   Header="TextNormalized"  Binding="{Binding Description}"  Width="*"  MinWidth="80" IsReadOnly="True" FontSize="12"  /> 
     </DataGrid.Columns> 
    </DataGrid> 

一些代碼隱藏:

Private ListData As New List(Of clsHexRowData) 

實例:

Public Sub New() 

    ' This call is required by the designer. 
    InitializeComponent() 

    Me.dgv.ItemsSource = Me.ListData 
    Me.ListData.Clear() 
    Dim item As New clsQueueItem 
    item.FromString("Hallo") 
    Me.AddItem(item) 
End Sub 

這是可見的,但在初始化頁面後添加新行時,項目不會更新,需要dgv.Items.Refresh,我不明白爲什麼。

回答

1

使用ObservableCollection(myclass)而不是列表。您將在添加或刪除項目時看到更改。

編輯

//add 
Application.Current.Dispatcher.BeginInvoke((Action)(()=> { Me.ListData.Add(new Item());})) 
+0

什麼了迅速的回答。非常感謝。現在我明白了,爲什麼我的其他項目(我的第一個項目)還有效因爲我沒有那樣使用更新的行。謝謝blindmeis – Nasenbaer 2012-02-20 11:45:03

+0

親愛的盲人。 VS現在拋出一個錯誤,因爲我需要在Dispatcher線程中添加和刪除項目。有沒有辦法避免進入UI線程,調度程序線程? – Nasenbaer 2012-02-20 12:36:45

+0

你必須在UI線程中添加它們。最簡單的方法是將你的添加和刪除委託給UI線程。 – blindmeis 2012-02-20 12:48:56