views:

55

answers:

1

I trying to bind List to Listbox. And at the Button1Click method new instance of MyClass adds in my List<>, but that not visible in my listbox. There my code:

       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;
                }
}

It is my form episode and 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",
                            });
}

What I do wrong?

+3  A: 

You should use ObservableCollection<Node> instead of List<Node>. ObservableCollection is a generic dynamic data collection that provides notifications (using an interface "INotifyCollectionChanged") when items get added, removed, or when the whole collection is refreshed. List does not implements INotifyCollectionChanged, which interface is used by WPF ListBox to update UI.

see

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