コレクションのプロパティが変更されたときにObservableCollectionを含むリストボックスを更新する際に問題が発生しました(リストからのアイテムの追加/削除は正常に機能します):
リストボックスが設定さItemsSource="{Binding Path=AllPerson}"
れ、コードビハインドのデータコンテキストが次のように設定されていますthis.DataContext = allPersonClass;
。
allPersonClass
含むObservableCollection<Person> allPerson
クラスPerson
には、Nameなどのプロパティが含まれています。
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はすでに作成されたアイテムを更新しません
何が間違っているのでしょうか?
これがlistBoxxamlのウィンドウです
<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"/>
これは、変更が行われる(Personにバインドされる)DetailViewウィンドウの一部です。
<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;
}
「ObservableCollectionallPerson」で変更が行われることに注意してください。listBoxのみが古いデータを表示し続けます