2010-02-15 49 views
2

我试图将列表绑定到列表框。在Button1Click方法中,MyClass的新实例添加到我的列表<>中,但在我的列表框中不可见。还有我的代码:为什么我的WPF绑定不起作用?

 public static class NotesEngine 
      { 
       public static List<Note> All; 

       static NotesEngine() 
       { 
        All = new List<Note> 
           { 
            new Note 
             { 
              Content = "test1", 
             } 
           }; 
       } 

       public static List<Note> GetNotes() 
       { 
        return All; 
       } 
} 

这是我的形式插曲和ObjectDataProvider的:

<ObjectDataProvider ObjectType="{x:Type NotesEngine}" x:Key="NotesList" MethodName="GetNotes"/> 

...... 

<TabItem Header="test" DataContext="{Binding Source={StaticResource NotesList}}"> 

       <ListBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
         ItemTemplate="{StaticResource NotesListBoxDataTemplate}" 
         ItemsSource="{Binding }"> 
       </ListBox> 
</TabItem> 

private void button2_Click(object sender, RoutedEventArgs e) 
{ 
    NotesEngine.All.Add(new Note 
          { 
           Content = "xx", 
           Images = new List<string>(), 
           LastEdit = DateTime.Now, 
           Title = "XASAC", 
          }); 
} 

我做什么了?

回答

3

您应该使用ObservableCollection<Node>而不是List<Node>ObservableCollection是一个通用的动态数据集合,当项目被添加,删除或整个集合被刷新时,提供通知(使用接口“INotifyCollectionChanged”)。列表不实现INotifyCollectionChanged,WPF ListBox使用哪个接口来更新UI。

看到

  1. ObservableCollection<(Of <(T>)>) Class
  2. An Introduction to ObservableCollection in WPF
  3. List vs ObservableCollection vs INotifyPropertyChanged in Silverlight