我查找了一些与我的问题类似的问题,但我无法弄清楚我的代码错误的原因。所以,
我有一个 WPF 示例应用程序来演示我遇到的问题。在这个应用程序中,有一个类 Item:
[Serializable]
class Item : ISerializable
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime DateStamp { get; set; }
public Item() { }
public Item(SerializationInfo info, StreamingContext context)
{
ID = (int)info.GetValue("ID", typeof(int));
Name = (string)info.GetValue("Name", typeof(string));
DateStamp = (DateTime)info.GetValue("DateStamp", typeof(DateTime));
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("ID", ID);
info.AddValue("Name", Name);
info.AddValue("DateStamp", DateStamp);
}
}
此外,还有另一个名为 Model 的类。它看起来像这样:
class Model : INotifyPropertyChanged
{
private ObservableCollection<Item> itemsList;
public ObservableCollection<Item> ItemsList
{
get { return itemsList; }
set
{
if (itemsList != value)
{
itemsList = value;
OnPropertyChanged("ItemsList");
}
}
}
public Model()
{
itemsList = new ObservableCollection<Item>();
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
有一个主窗口,上面有一个列表框和 3 个按钮:
public partial class MainWindow : Window
{
private Model model;
private static int counter = 0;
public MainWindow()
{
InitializeComponent();
model = new Model();
listBoxItems.ItemsSource = model.ItemsList;
}
private void AddMoreSampleItem(object sender, RoutedEventArgs e)
{
model.ItemsList.Add(new Item
{
ID = ++counter,
Name = "Sample " + counter,
DateStamp = DateTime.Now.Date
});
}
private void Button1_Click_Serialize(object sender, RoutedEventArgs e)
{
using (Stream stream = File.Open("D:\\sample.qwertyasdf", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
{
IFormatter bf = new BinaryFormatter();
bf.Serialize(stream, model.ItemsList);
stream.Close();
}
}
private void Button2_Click_Deserialize(object sender, RoutedEventArgs e)
{
using (Stream stream = File.Open("D:\\sample.qwertyasdf", FileMode.Open, FileAccess.Read, FileShare.None))
{
IFormatter bf = new BinaryFormatter();
model.ItemsList = (ObservableCollection<Item>)bf.Deserialize(stream);
stream.Close();
}
}
}
在窗口的构造函数中,我将列表框的 ItemsSource 属性设置为“模型”对象的 ItemsList 属性: listBoxItems.ItemsSource = model.ItemsList;
现在,我认为,由于 ItemsList 实现了 INotyfyPropertyChanged,每次 model.ItemsList 属性更改其值时,它都应该引发属性更改事件,并且列表框应该自动跟随更改。
但是相反,列表框的内容没有改变,当我单击将示例项目添加到列表中的按钮时,它似乎不再反应了。
列表框:
<ListBox x:Name="listBoxItems" ItemsSource="{Binding UpdateSourceTrigger=PropertyChanged}" ItemTemplate="{StaticResource ListTemplate}" HorizontalAlignment="Left" Height="100" Margin="10,78,0,0" VerticalAlignment="Top" />
如果有人发现此失败的原因,请帮帮我,我已经被这个问题困扰了 4 天了。然而,似乎数据绑定并没有中断,但我不确定。