为什么我的 WPF 绑定不起作用?
我试图将列表绑定到列表框。在 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",
});
}
我做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该使用
ObservableCollection
而不是List
。 ObservableCollection 是一个通用的动态数据集合,它在添加、删除项目或刷新整个集合时提供通知(使用接口“INotifyCollectionChanged
”)。 List 未实现INotifyCollectionChanged
,WPF ListBox 使用该接口来更新 UI。请参阅
You should use
ObservableCollection<Node>
instead ofList<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 implementsINotifyCollectionChanged
, which interface is used by WPF ListBox to update UI.see