gpt4 book ai didi

c# - MVVM跟踪 View 模型中的问题

转载 作者:行者123 更新时间:2023-12-03 10:59:23 25 4
gpt4 key购买 nike

我的要求是跟踪数据上下文中发生的更改,并且当属性更改时,我已将新的 View 模型添加为历史记录项。第一次它正常工作时,进行第二次更改时,第二个也反射(reflect)在历史记录的已添加项中。我是做错了请帮忙。

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));
}
}

谢谢

最佳答案

这很正常,因为您的对象是reference type。您应该制作一个deep copy,以反射(reflect)历史记录列表中的更改

尝试这样的事情

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);
}
}

关于c# - MVVM跟踪 View 模型中的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22195049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com