开发者

WPF binding to entity framework not updating

I have some binding that is binding to an object defined by the entity framework. Some of my bindings update ok while others do not. The best way to explain is via an example, I have something like this:

<TextBlock Text="{Binding Path=FirstName}"/>
<TextBlock Text="{Binding Path=LastName}"/>
<TextBlock Text="{Binding Path=Role.Name}"/>

In this case the text in the first 2 textblocks update fine as soon as the property of the object is changed. In the case of the last one nothing happens. I can see why this is happening. The entity framework has a property RoleID which is getting updated and it is raising the property changed event for RoleID but afaik it does not raise such an event for Role. So the binding does not know anything has changed. Possible solutions I can see are to get the entity framework to raise the property changed event for Role when RoleID is changed, or to get the binding to look for changes in RoleID instead of Role. I'm not sure how to do either of those.

Thanks in advance for any replies, Micha开发者_运维技巧el


I found a solution. As Jerry said, the entity object needs to raise a property changed event. The problem is the entity framework only raises an event for RoleID but not Role. I was trying to raise my own event by calling ReportPropertyChanged but this was giving an error saying the property does not exist. The solution is to call OnPropertyChanged("Role") instead of ReportPropertyChanged. This can be done in a partial method so that when RoleID is changed then an event is raise for role also. Something like this

partial void OnRoleIDChanged()
{
    OnPropertyChanged("Role");
}


Two things you should know:

  1. If your class properties do not implement INotifyPropertyChanged then changes to the underlying data will not be reflected in the UI.

  2. If you do not add UpdateSourceTrigger=PropertyChanged to your binding then the changes to the UI will not be reflected in the underlying data (until you leave the field).

I hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜