这个问题已经困扰了一段时间,阻碍了项目的进展。考虑一个 WPF XAML 表单,其中的控件绑定到 ViewModel 上。(我正在使用 Caliburn.Micro MVVM 框架和 Entity Framework 进行数据处理)。一个
问题在于
更新:为了澄清,我认为问题在于我需要能够连接到一个事件或回调,当所有绑定完成更新时触发,这样我就可以连接 PropertyChanged 事件处理程序。
Initialize()
方法由外壳调用以从数据库中加载表单数据并设置 PropertyChanged 事件处理程序。有一个 IsDirty
标志来跟踪表单中是否有更改后的数据。有一个“保存”按钮绑定到 IsDirty
属性,当数据发生更改时,该按钮就会被启用。// Sample code; forms have many controls....
// this is the property that the controls are bound to
public Entity BoundData { get; set; }
public void Initialize()
{
// this is an example line where I query the database from the Entity Framework ObjectContext...
BoundData = objectContext.DataTable.Where(entity => entity.ID == 1).SingleOrDefault();
// this is to cause the form bindings to retrieve data from the BoundData entity
NotifyOfPropertyChange("BoundData");
// wire up the PropertyChanged event handler
BoundData.PropertyChanged += BoundData_PropertyChanged;
IsDirty = false;
}
void BoundData_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
IsDirty = true;
}
// implementation of the IsDirty flag
public bool IsDirty
{
get
{
return _isDirty;
}
set
{
_isDirty = value;
NotifyOfPropertyChange("IsDirty");
}
}
问题在于
BoundData_PropertyChanged
事件处理程序在表单从数据库初始化后被触发,而此时 Initialize()
方法已经完成。因此,IsDirty
标志被设置为 true,保存按钮被启用,即使表单刚刚加载并且用户还没有更改任何内容。我错过了什么吗?毫无疑问,这是一个常见的问题,但我一直找不到一个好的解决方案。这是我的第一个MVVM项目,所以很可能我漏掉了一些基本概念。更新:为了澄清,我认为问题在于我需要能够连接到一个事件或回调,当所有绑定完成更新时触发,这样我就可以连接 PropertyChanged 事件处理程序。