JD2022-TU1/main/tools/framework/JD.Collections/Observable.cs

51 lines
No EOL
1.4 KiB
C#

using System;
using System.ComponentModel;
using JD.Collections.Interfaces;
namespace JD.Collections
{
/// <summary>
/// Base class for objects with a property changed event.
/// </summary>
public class Observable : INotifyPropertyChanged, IObservableItem
{
/// <summary>
/// Sets the value of the property, triggers the expected events.
/// </summary>
protected virtual void SetValue<T>(ref T field, T newValue, string propertyName)
{
if (!Equals(field, newValue))
{
field = newValue;
OnPropertyChanged(propertyName);
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
var args = new PropertyChangedEventArgs(propertyName);
handler?.Invoke(this, args);
OnChanged(args);
}
public event EventHandler Changed;
protected virtual void OnChanged(EventArgs e)
{
Changed?.Invoke(this, e);
}
/// <summary>
/// Allows to unregister all handlers. Useful when cloning for example.
/// </summary>
protected virtual void ClearEvents()
{
Changed = null;
PropertyChanged = null;
}
}
}