我的要求是追踪datacontext中发生的变化,当属性发生变化时,我将新的viewmodel添加为历史记录项。第一次正常工作时,第二次更改时,第二次更改也反映在History已添加的项目中。我做错了,请帮忙。
public partial class MainWindow : Window
{
private List<Employee> history;
public List<Employee> History
{
get { return history; }
set { history = value; }
}
public MainWindow()
{
InitializeComponent();
History = new List<Employee>();
this.DataContext = new Employee();
if (DataContext != null)
{
this.DataContextChanged += new DependencyPropertyChangedEventHandler(MainWindow_DataContextChanged);
(this.DataContext as Employee).PropertyChanged += new PropertyChangedEventHandler(MainWindow_PropertyChanged);
}
}
private void MainWindow_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
History.Add((Employee)this.DataContext);
}
private void MainWindow_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
}
private void button1_Click(object sender, RoutedEventArgs e)
{
}
}
public class Employee : INotifyPropertyChanged
{
private List<Employee> history;
public List<Employee> History
{
get { return history; }
set { history = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; RaisePropertyChanged("Name"); }
}
private string ph;
public string PH
{
get { return ph; }
set { ph = value; RaisePropertyChanged("PH"); }
}
private DateTime dob;
public DateTime DOB
{
get { return dob; }
set { dob = value; RaisePropertyChanged("DOB"); }
}
private int age;
public int Age
{
get { return age; }
set { age = value; RaisePropertyChanged("Age"); }
}
public Employee()
{
History = new List<Employee>();
Name = "MKumar";
Age = 10;
DOB = new DateTime(2004, 7, 8);
PH = "999999999";
PropertyChanged += new PropertyChangedEventHandler(Employee_PropertyChanged);
}
private void Employee_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
History.Add(this);
//throw new NotImplementedException();
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string name)
{
if (PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
由于
答案 0 :(得分:3)
这是正常的,因为您的对象是reference type
。您应该设置deep copy
以反映历史记录列表中的变化
尝试这样的事情
private void Employee_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
var empCloned = DeepClone(this);
History.Add(empCloned);
//throw new NotImplementedException();
}
深层复制
private T DeepClone<T>(T obj)
{
using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;
return (T) formatter.Deserialize(ms);
}
}