开发者

Why my WPF binding not work?

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:

<Ob开发者_如何转开发jectDataProvider 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?


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜