When reading Pro WPF in C # 2010, the author writes:
"You can raise an event for each property. In this case, the event should be named PropertyNameChanged (for example, UnitCostChanged). You can activate the event when the property changes.
Can anyone confirm this feature? I experimented and was unable to reproduce this behavior (I want to see if this works, so I can experiment a little with System.Reflection.Emit to create dynamic types)
EDIT: I must clarify that the main focus is on introducing change notification WITHOUT the implementation of INotifyPropertyChanged, as this is what the book is talking about
Here's the POCO I'm testing with:
public class Employee { private string _FirstName; public string FirstName { get { return _FirstName; } set { if (_FirstName != value) { _FirstName = value; if (FirstNameChanged != null) { FirstNameChanged(this, new PropertyChangedEventArgs("FirstName")); } } } } }
I linked it to a DataGrid and turned on the timer in the background to change the FirstName property randomly every few seconds, but the DataGrid never fires
<DataGrid x:Name="dgEmployees" ItemsSource="{Binding ElementName=mainWindow, Path=MyEmployees}"> <DataGrid.Columns> <DataGridTextColumn Header="FirstName" Binding="{Binding Path=FirstName}" /> </DataGrid.Columns> </DataGrid>
The FirstNameChanged event is always null (I thought the binding mechanism could automatically subscribe to it if it detects it in accordance with the naming convention). MyEmployees is just an ObservableCollection
Can someone confirm if the author mentions this function, does it really work, and if I am wrong?
EDIT: in the interest of anyone who believes that I am misinterpreting the text:
"You can use three approaches to solve this problem:
You can make each property in the Product class dependent, using which you learned in Chapter 4. (In this case, your class must be derived from DependencyObject.) Although this approach allows WPF to do the work for you (which is nice), it makes the most sense in classes of elements that have a visual appearance in the window. This is not the most natural approach for data classes such as Product.
You can create an event for each property. In this case, the event should have name PropertyNameChanged (for example, UnitCostChanged). Its up to you to fire the event when the property changes.
You can implement the System.ComponentModel.INotifyPropertyChanged interface, which requires a single event called PropertyChanged. Then you should raise the PropertyChanged event whenever the property changes and indicates which property has changed by providing the property name as a string. Its up to you to raise this event when the property changes, but you do not need to define a separate event for each property. "