To implement data binding in WPF, according to MS, "the class must ensure that notification properties are correctly changed." [ here)
AFAIK, the part of setting it up means taking the following steps if they are not set up in the class yet (ref this article on MSDN)
set
...
// Create the OnPropertyChanged method to raise the event protected void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } }
If I already have many existing classes that do not take any of these steps, what is the best way to change these classes so that they only change as much as necessary to conform to these standards?
If you need a solution with the smallest possible code possible, then you want a Fody PropertyChanged weaver . It is installed as a NuGet package with Install-Package PropertyChanged.Fodyor through the VS Package Manager dialog.
Install-Package PropertyChanged.Fody
[ImplementPropertyChanged], . , , , . !
[ImplementPropertyChanged]
, , , " " .
[CallerMemberName] # 5,
protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "") { ... }
CallerMemberName.
:
public DateTime Time { get { return this.model.DateTime; } set { this.model.DateTime = value; NotifyPropertyChanged(); } }
class IWillNotifyYou : INotifyPropertyChanged { private int _firstProperty; public int FirstProperty { get { return _firstProperty; } set { if (value != _firstProperty) { _firstProperty = value; OnPropertyChanged("FirstProperty"); } } } private string _secondProperty; public string SecondProperty { get { return _secondProperty; } set { if (value != _secondProperty) { _secondProperty = value; OnPropertyChanged("SecondProperty"); } } } private void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; }
, , FirstPropertyChanged
": INotifyPropertyChanged" :
Public class Test : INotifyPropertyChanged { }
ReSharpers ( ReSharper ).
OnPropertyChanged("PropertyName")
, XAML .
, . WPF MVVM (Model-View-ViewModel). , ( ).
, Business Objects, , INotifyPropertyChanged. WPF ViewModel. ViewModel - , View ( WPF) Model.
INotifyPropertyChanged
ViewModel
View
Model
Model INotifyPropertyChanged, . ViewModel , ( ), , , , , -.