INotifyPropertyChanged With Generic Set C# with Example

INotifyPropertyChanged With Generic Set C# with Example

The NotifyPropertyChangedBaseclass below defines a generic Set method that can be called from any derived 
public class NotifyPropertyChangedBase : INotifyPropertyChanged 
protected void RaisePropertyChanged([CallerMemberName] string propertyName = null) => 
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 
public event PropertyChangedEventHandler PropertyChanged; 
public virtual bool Set(ref T field, T value, [CallerMemberName] string propertyName = null) 
if (Equals(field, value)) 
return false; 
storage = value; 
return true; 
To use this generic Set method, you simply need to create a class that derives from NotifyPropertyChangedBase. 
public class SomeViewModel : NotifyPropertyChangedBase 
private string _foo; 
private int _bar; 
public string Foo 
get { return _foo; } 
set { Set(ref _foo, value); } 
public int Bar 
get { return _bar; } 
set { Set(ref _bar, value); } 
As shown above, you can call Set(ref _fieldName, value); in a property's setter and it will automatically raise a 
PropertyChanged event if it is needed. 
You can then register to the PropertyChanged event from another class that needs to handle property changes. 
public class SomeListener 
public SomeListener() 
_vm = new SomeViewModel(); 
_vm.PropertyChanged += OnViewModelPropertyChanged; 
private void OnViewModelPropertyChanged(object sender, PropertyChangedEventArgs e) 
Console.WriteLine($"Property {e.PropertyName} was changed."); 

private readonly SomeViewModel _vm; 

Parameter Details 
EventArgsT The type that derives from EventArgs and contains the event parameters. 
EventName The name of the event. 
HandlerName The name of the event handler. 
SenderObject The object that's invoking the event. 
EventArguments An instance of the EventArgsT type that contains the event parameters. 
An event is a notification that something has occurred (such as a mouse click) or, in some cases, is about to occur 
(such as a price change). 
Classes can define events and their instances (objects) may raise these events. For instance, a Button may contain a 
Click event that gets raised when a user has clicked it. 
Event handlers are then methods that get called when their corresponding event is raised. A form may contain a 
Clicked event handler for every Button it contains, for instance. 

0 Comment's

Comment Form