当集合的属性更改(添加/删除项目)时,我遇到了更新包含ObservableCollection的Listbox的问题:
Listbox设置为ItemsSource="{Binding Path=AllPerson}"
,代码后台中的数据上下文设置如下:this.DataContext = allPersonClass;
allPersonClass
包含ObservableCollection<Person> allPerson
类Person
包含像Name等属性。
我重写了person的ToString
方法,以返回Name
属性,因此listBox显示有效数据。
我尝试让Person
实现INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void onPropertyChanged(object sender, string propertyName) {
if (this.PropertyChanged != null) {
PropertyChanged(sender, new PropertyChangedEventArgs(propertyName));
}
}
public string Name {
get { return name; }
set {
name = value;
onPropertyChanged(this, "allPersonClass");
}
}
每个属性的设置器都有
onPropertyChanged(this, "propertyName");
,这个语句会被执行,但listBox从未更新已创建的项。你知道可能有什么问题吗?
以下是包含listBox XAML的窗口:
<Button x:Name="btnDetail" Content="Detail" HorizontalAlignment="Left" Margin="361,249,0,0" VerticalAlignment="Top" Width="75" Click="ButtonDetailClick"/>
<ListBox x:Name="listPerson" ItemsSource="{Binding Path=AllPerson}" HorizontalAlignment="Left" Height="170" Margin="33,29,0,0" VerticalAlignment="Top" Width="155" IsSynchronizedWithCurrentItem="True"/>
<Button x:Name="btnLoad" Content="Load" HorizontalAlignment="Left" Margin="58,249,0,0" VerticalAlignment="Top" Width="75" Click="btnLoad_Click"/>
<Button x:Name="btnSave" Content="Save" HorizontalAlignment="Left" Margin="138,249,0,0" VerticalAlignment="Top" Width="75" Click="ButtonSaveClick"/>
这是DetailView窗口的一部分,用于进行修改(绑定到Person)
<TextBox Text="{Binding Path=Name}" Height="23" HorizontalAlignment="Left" Margin="118,20,0,0" Name="txtName" VerticalAlignment="Top" Width="141" />
这里是AllPersonClass的一部分:
public class AllPersonClass {
private ObservableCollection<Person> allPerson;
public AllPersonClass() {
allPerson = new ObservableCollection<Person>();
}
public ObservableCollection<Person> AllPerson {
get { return allPerson; }
set { allPerson = value; }
}
public void addPerson(Person newPerson) {
allPerson.Add(newPerson);
}
public Person getPerson(int personIndex) {
return allPerson[personIndex];
}
}
编辑
这里是保存详细视图更改的相关方法部分。
private void OnBtnSaveClick(object sender, RoutedEventArgs e) {
person.Name = txtName.Text;
person.SurName = txtSurName.Text;
}
请注意,更改只在“ObservableCollection allPerson”中进行,listBox仍显示旧数据。
allPersonClass
类的实现。 - Jehof