Created
March 24, 2019 10:08
-
-
Save Goncharuk-Nikita/e5f485ef5a80362e89133984f9289076 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Concurrent; | |
using System.ComponentModel; | |
using System.Runtime.CompilerServices; | |
[AttributeUsage(AttributeTargets.Method)] | |
public sealed class NotifyPropertyChangedInvocatorAttribute : Attribute | |
{ | |
public NotifyPropertyChangedInvocatorAttribute() | |
{ | |
} | |
public NotifyPropertyChangedInvocatorAttribute([NotNull] string parameterName) | |
{ | |
ParameterName = parameterName; | |
} | |
[CanBeNull] public string ParameterName { get; private set; } | |
} | |
public class Bindable : INotifyPropertyChanged, INotifyPropertyChanging | |
{ | |
readonly ConcurrentDictionary<string, object> _properties = new ConcurrentDictionary<string, object>(); | |
public event PropertyChangedEventHandler PropertyChanged; | |
public event PropertyChangingEventHandler PropertyChanging; | |
protected bool CallPropertyChangeEvent { get; set; } = true; | |
[NotifyPropertyChangedInvocator] | |
protected void OnPropertyChanged([CallerMemberName] string propertyName = null) | |
{ | |
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); | |
} | |
protected void OnPropertyChanging([CallerMemberName] string propertyName = null) | |
{ | |
PropertyChanging?.Invoke(this, new PropertyChangingEventArgs(propertyName)); | |
} | |
protected T Get<T>(T defValue = default(T), [CallerMemberName] string name = null) | |
{ | |
return !string.IsNullOrEmpty(name) && _properties.TryGetValue(name, out var value) | |
? (T)value | |
: defValue; | |
} | |
protected bool Set(object value, [CallerMemberName] string name = null) | |
{ | |
if (string.IsNullOrEmpty(name)) | |
return false; | |
var isExists = _properties.TryGetValue(name, out var getValue); | |
if (isExists && Equals(value, getValue)) | |
return false; | |
if (CallPropertyChangeEvent) | |
OnPropertyChanging(name); | |
_properties.AddOrUpdate(name, value, (s, o) => value); | |
if (CallPropertyChangeEvent) | |
OnPropertyChanged(name); | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment