【问题标题】:Why my WPF binding not work?为什么我的 WPF 绑定不起作用?
【发布时间】:2011-01-16 21:16:02
【问题描述】:

我试图将 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",
                            });
}

我做错了什么?

【问题讨论】:

    标签: c# wpf binding listbox objectdataprovider


    【解决方案1】:

    您应该使用ObservableCollection&lt;Node&gt; 而不是List&lt;Node&gt;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

    【讨论】:

      猜你喜欢
      • 2011-09-29
      • 2016-04-10
      • 2022-11-20
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 2020-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多