2

我试图将列表绑定到列表框。在 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",
                            });
}

我做错了什么?

4

1 回答 1

3

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

  1. ObservableCollection<(Of <(T>)>) 类
  2. WPF 中的 ObservableCollection 简介
  3. Silverlight 中的 List vs ObservableCollection vs INotifyPropertyChanged
于 2010-02-15T06:46:24.227 回答