【发布时间】:2017-09-17 08:07:45
【问题描述】:
您好,我想将自定义对象列表绑定到 WPF 中的 ListBox。 我有下一个代码:
private List<User> users = new List<User>();
public MainWindow()
{
InitializeComponent();
this.users = User.GetAllUsersFromFile();
this.listBox.DataContext = users;
this.listBox.ItemsSource = users;
}
还有 XML:
<ListBox x:Name="listBox" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
还有用户类:
private string name;
private byte[] avatar;
public string Name
{
get
{
return this.name;
}
set
{
if (value.Any(c => c == ' '))
throw new Exception("Invalid name. (It cannot contain spaces)");
this.name = value;
}
}
public byte[] Avatar
{
get
{
return this.avatar;
}
set
{
this.avatar = value;
}
}
初始列表按预期显示,但如果向列表中添加(或删除)新项目,则列表不会更新。
【问题讨论】:
-
使用
ObservableCollection<User> users应该没问题。 -
列表是动态的还是静态的?
-
为什么是
this.listBox.DataContext = users;?这没有任何目的。十分钟阅读文档可以让您在两天内为随机属性分配任意值。
标签: c# wpf data-binding