我正在构建 WPF 应用程序,并且我想要能够检查实体是否为 IsDirty,所以我在网上找到了这个解决方案:
private bool isDirty;
public virtual bool IsDirty
{
get { return isDirty; }
set { isDirty = value; }
}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
OnPropertyChanged(true, propertyName);
}
protected void OnPropertyChanged(bool makeDirty, [CallerMemberName] string propertyName = "")
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
if (makeDirty)
{
isDirty = makeDirty;
}
}
然后我可以像这样使用它
[Required(ErrorMessage = ErrorMessages.DescriptionRequired)]
[StringLength(60, ErrorMessage = ErrorMessages.DescriptionLength60)]
public string Description
{
get { return description; }
set
{
if (description != value)
{
description = value;
OnPropertyChanged();
}
}
}
而且它似乎有效,只要属性发生更改,实体就会变脏,因为调用了 OnPropertyChanged。我遇到的问题是,当我从数据库加载一个实体(或实体集合)时,就会调用 onpropertychanged:
SomeEntitiesCollection = new Service().SomeEntities();
然后每个出现的实体都被标记为脏,除了通过一个循环并将 IsDirty 设置回 false 之外,我无法在它周围找到任何东西。还有其他方法可以实现吗?
问候