Do I need to implement INotifyPropertyChanged when using EF Code-First?

前端 未结 2 538
一整个雨季
一整个雨季 2021-01-21 15:53

I\'m noticing that when using EF CodeFirst, and binding my UI to an ObservableCollection via the DBSet.Local property recommended here, that the UI will up

相关标签:
2条回答
  • 2021-01-21 16:29

    This is a bad answer, but I'm including it here to contribute to understanding of the question.

    It would seem that the answer would be "YES" you must implement INotifyPropertyChanged in your model for controls to get notified of their change (thus allow controls to update when they are changed).

    But if the above is true why can a TextBox databound to a entity cause changes in other controls.

    Try it! For example you can bind a TextBox's Text property to the SelectedItem of a DataGrid (which is bound to a ObservableCollection from a .Local) with UpdateSourceTrigger=PropertyChanged. Now run and select a row in the DataGrid and edit the TextBox and the text in the DataGrid row will update realtime! How does the text box force that change in the DataGrid!?!?!

    Here is the binding code of the above example:

    <TextBox Text="{Binding Path=SelectedItem.Name, UpdateSourceTrigger=PropertyChanged}" />
    

    This works with a TextBox not just on the same View, but even if the entity is gathered from SelectedItem and passed in to a second view which then has a TextBox that binds to the entity. (Manages to update the first window's DataGrid realtime!)

    This is super cool! Now I wish I could find a way to in code SelectedItem.Name = "New Name", because no matter what I try that will not update the DataGrid. (I can't refresh the DataGrid directly because I'm using MVVM and have no access to it)

    Note: I'm using EF4.1 with DBContext & POCO entities (ie. simple classes that do not implement any interfaces)

    0 讨论(0)
  • 2021-01-21 16:33

    Yes,

    Every element that you want to update the UI when a property of it is modified must implement INotifyPropertyChange.

    The reason for this is, the UI knows when the collection changes, but if the property of one of those elements changes, there is no CollectionChanged event associated with it, so the UI is ignorant

    See also: Entity Framework CTP5 Code First, WPF - MVVM modeling

    0 讨论(0)
提交回复
热议问题