积极答复者
wpf 怎么为ADO.NET实体数据模型中的类 实现INotifyPropertyChanged接口

问题
答案
-
你好,
EntityFramework自动生成的已经为我们实现了INotifyPropertyChanged了,还有自动生成不代表我们不能修改,你完全可以去修改它。你试试看。
Sincerely,
Bob Bao [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
- 已标记为答案 cheamy 2011年1月24日 14:41
全部回复
-
你好,
EntityFramework自动生成的已经为我们实现了INotifyPropertyChanged了,还有自动生成不代表我们不能修改,你完全可以去修改它。你试试看。
Sincerely,
Bob Bao [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
- 已标记为答案 cheamy 2011年1月24日 14:41
-
你好 Cheamy,
EntityFramework中的一些属性比如(scalar properties)实现了INotifyPropertyChanged这个接口,但是对于其他一些属性,比如(Navigation properties)是不支持INotifyPropertyChanged,是不支持,并不是没有实现(我个人是这样理解的)。
对于你的问题,首先我会先给你一个解决方案,然后我会向你解释一下EntityFramework中的属性工作原理(有兴趣的话可以看一下)。
你可以用下面的代码区完成属性的变化通知:(这里的属性是Role)
public partial class User
{
private void RoleChanged(Object sender, CollectionChangeEventArgs e)
{
// 执行protected OnPropertyChanged 方法
// 在这里出发INotifyPropertyChanged.PropertyChanged 事件
OnPropertyChanged("Role");
}// 创建一个默认的构造函数去注册Role属性的改变
public User()
{
this.RoleReference.AssociationChanged += RoleChanged;
}
}下面我给你解释一下原因(个人的理解,希望能给你一些帮助):
EntityFramework就像我前面说的,针对一些属性是可以完成属性的变更通知的,但是对于另一些属性是没有实现属性变更通知的,原因是这样,对于那些Navigation properties,在自动生成的时候,其实是生成了两个这样的属性,比如这里我拿Role举例,生成的一个将会是“Role”,而另一个会是Reference以附加的形式在原属性上,例如(RoleReference),第一个属性Role就是正常的,我们可以使用Get和Set得到他的值的属性,这里我就不多讲了。对于第二个属性RoleReference,其实就是EntityReference,对于EntityReference你可以Google一下,应该有很多的信息。
上面是关于EntityFramework中属性的描述就到这里,下面回到你最关心的问题上。如果你设置Role属性的PropertyChanged,这个不会被触发,如果我看了一下自动生成的代码,关键部分是:
Public Property Role() As Role
Get
Return CType(Me,Global.System.Data.Objects.DataClasses.IEntityWithRelationships).RelationshipManager.GetRelatedReference(Of Role)("MyDatabaseModel.FK_Users_Roles", "Roles").Value
End Get
Set
CType(Me,Global.System.Data.Objects.DataClasses.IEntityWithRelationships).RelationshipManager.GetRelatedReference(Of Role)("MyDatabaseModel.FK_Users_Roles", "Roles").Value = value
End Set
End Property我发现“ReportPropertyChanged ”没有在这里执行,所以就像没有实现INotifyPropertyChanged接口一样。因此, 我一般都是用“AssociationChanged”这个事件去监听属性的改变,然后用他去执行PropertyChanged,去完成我们想要的效果。
以上是我的经验,如果有说错的地方可以一起讨论,希望这些我所了解的信息可以对你有所帮助。
Best regards,
Sheldon _Xiao [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
- 已建议为答案 Jarrey 2011年1月24日 15:01