LotSizingDataModel.Core 2.0.1
Core domain model, shared abstractions and XML-serializable entities.
Loading...
Searching...
No Matches
ModelObject.cs
Go to the documentation of this file.
1using System;
2using System.Collections.Generic;
3using System.ComponentModel;
4using System.Runtime.CompilerServices;
5
7
8/// <summary>
9/// Base class for model objects that notify listeners when one of their
10/// properties changes.
11///
12/// This class is compatible with XML serialization. Events are not serialized.
13/// </summary>
14[Serializable]
15public abstract class ModelObject : INotifyPropertyChanged
16{
17 /// <summary>
18 /// Raised when the value of a property changes.
19 /// </summary>
20 [field: NonSerialized]
21 public event PropertyChangedEventHandler? PropertyChanged;
22
23 /// <summary>
24 /// Assigns a new value to a backing field and raises
25 /// <see cref="PropertyChanged"/> when the value has actually changed.
26 /// </summary>
27 /// <typeparam name="T">Type of the property.</typeparam>
28 /// <param name="field">Backing field of the property.</param>
29 /// <param name="value">New value.</param>
30 /// <param name="propertyName">
31 /// Name of the modified property. It is normally supplied automatically
32 /// by the compiler.
33 /// </param>
34 /// <returns>
35 /// <see langword="true"/> when the value has changed;
36 /// otherwise, <see langword="false"/>.
37 /// </returns>
38 protected bool SetProperty<T>(
39 ref T field,
40 T value,
41 [CallerMemberName] string? propertyName = null)
42 {
43 // Avoid unnecessary notifications if the value hasn't changed
44 if (EqualityComparer<T>.Default.Equals(field, value))
45 {
46 return false;
47 }
48
49 // Update the backing field and notify listeners
50 field = value;
51 OnPropertyChanged(propertyName);
52
53 return true;
54 }
55
56 /// <summary>
57 /// Raises the <see cref="PropertyChanged"/> event.
58 /// </summary>
59 /// <param name="propertyName">Name of the modified property.</param>
60 protected virtual void OnPropertyChanged(
61 [CallerMemberName] string? propertyName = null)
62 {
63 // Invoke the event if there are any subscribers
64 PropertyChanged?.Invoke(
65 this,
66 new PropertyChangedEventArgs(propertyName));
67 }
68}
Base class for model objects that notify listeners when one of their properties changes.
PropertyChangedEventHandler? PropertyChanged
Raised when the value of a property changes.
virtual void OnPropertyChanged([CallerMemberName] string? propertyName=null)
Raises the PropertyChanged event.
bool SetProperty< T >(ref T field, T value, [CallerMemberName] string? propertyName=null)
Assigns a new value to a backing field and raises PropertyChanged when the value has actually changed...