我查找了一些类似于我的问题的问题,但我无法弄清楚为什么我的代码错了。所以,
我有一个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();
}
}
}
在窗口的构造函数中,我将listbox的ItemsSource属性设置为“model”对象的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天了。然而,看起来数据绑定并没有破坏,但我不确定。
答案 0 :(得分:0)
如果您希望在更改数据绑定属性时更新UI,则需要在属性已更改的项目上实现INotifyPropertyChanged
接口。您的模型已实现它,但您的Item
类没有实现它。因此,如果更改了item.Name
属性,则UI中将不会更新。