开发者

Why my WPF binding not work?

开发者 https://www.devze.com 2022-12-20 00:04 出处:网络
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:

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

精彩评论

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