为什么我的WPF绑定不起作用?

时间:2010-02-15 06:30:32

标签: c# wpf binding listbox objectdataprovider

我尝试将List绑定到Listbox。在Button1Click方法中,MyClass的新实例在我的List<>中添加,但在我的列表框中不可见。我的代码是:

       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",
                            });
}

我做错了什么?

1 个答案:

答案 0 :(得分:3)

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

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