[英]DataGrid´s SelectedItem lost Binding after UnitOfWork.SaveChanges
我目前正在开发一个使用 EntityFramework 的应用程序。 在这个应用程序中,有一个 DataGrid,SelectedItem 绑定到 ViewModel 上的一个属性:
<DataGrid AutoGenerateColumns="False"
CanUserDeleteRows="True"
IsReadOnly="True"
IsSynchronizedWithCurrentItem="False"
ItemsSource="{Binding ZuvTextCollection}"
SelectedItem="{Binding SelectedEntity,
UpdateSourceTrigger=PropertyChanged,
Mode=TwoWay}">
现在我遇到的问题是,一旦存储了数据,与 SelectedItem 的绑定似乎几乎丢失了。
编辑:我忘记了很重要的一点! 抱歉! 并且此错误仅在创建新记录后发生。
protected override void OnSave()
{
if (!this.OnCanSave())
{
return;
}
this.UnitOfWork.SaveChanges();
this.IsDirty = this.UnitOfWork.ChangeTracker.HasChanges;
}
调用 this.UnitOfWork.SaveChanges 后,绑定到 ViewModel 中的 Property 不再存在。 DataGrid 中的行确实可以选择,但是Selection 的变化没有到达ViewModel。
它可能是什么?
PS:我已经阅读了以下帖子http://www.devexpress.com/Support/Center/Question/Details/Q509665但我必须承认这让我不知道如何解决我的问题。 谢谢你的帮助!
@lll:我忘记了很重要的一点! 抱歉! 并且此错误仅在创建新记录后发生。
public ZuvText SelectedEntity
{
get
{
return this.selectedEntity;
}
set
{
var entity = value;
if (this.selectedEntity != null)
{
this.selectedEntity.PropertyChanged -= this.OnEntityPropertyChanged;
this.selectedEntity.DisableContinuousValidation();
}
if (entity != null)
{
entity.PropertyChanged += this.OnEntityPropertyChanged;
entity.EnableContinuousValidation();
}
this.SetProperty(ref this.selectedEntity, entity);
}
}
实体是在保存之前设置的,即在创建新项目时。 (当光标移动到新实体时,它是 SelectedEntity)
现在,一位队友已经找到了原因。 在我们的实体 Equals 和 GetHashCode 的基类中被覆盖:
public bool Equals(TEntity other)
{
if (object.ReferenceEquals(null, other))
{
return false;
}
if (object.ReferenceEquals(this, other))
{
return true;
}
return this.id == other.Id;
}
public override bool Equals(object obj)
{
if (object.ReferenceEquals(null, obj))
{
return false;
}
if (object.ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != this.GetType())
{
return false;
}
return this.Equals(obj as TEntity);
}
public override int GetHashCode()
{
// ReSharper disable once NonReadonlyFieldInGetHashCode
return this.id.GetHashCode();
}
GetHashCode 的覆盖导致 id 在存储之前和之后提供不同的 hashCode 并且不再检测到对象。 现在我们已经注释掉了 GetHashCode 的覆盖。 但是,我不知道这个问题的真正解决方案。 我的队友已经在寻找解决方案,但也许您有想法?
我们有解决方案! DataGrid 选择器无法找到所选对象,更新 ID 后。 这就是我们现在将实际的 EntityCollection 放在适配器或包装类中的原因。
public class ZuvTextAdapter
{
public ZuvText ZuvText
{
get;
set;
}
}
DataSorce 看起来像这样:
public ObservableCollection<ZuvTextAdapter> ZuvTextAdapterCollection...
并且只是选定的实体:
public ZuvTextAdapter SelectedAdapter
因此,我们的 GetHeshCode 解决了问题,保存后绑定工作正常。 (由我的队友解决!)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.