I like to do some less repetitive and wasteful coding of full properties that needs the INotifyPropertyChanged
interface and do custom attribute.
Background
Today, in order to use MVVM
with dynamic updating values in the window, we need to do the following:
private string _SomeProp;
public string SomeProp
{
get => _SomeProp;
set
{
_SomeProp = value;
OnPropertyChanged();
}
}
public void OnPropertyChanged([CallerMemberName] string name = null)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
public event PropertyChangedEventHandler PropertyChanged;
Suggestion and the Problem
The custom attribute
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace MyProject.Models;
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class PropertyChangedAttribute : Attribute, INotifyPropertyChanged
{
public PropertyChangedAttribute([CallerMemberName] string propertyName = null)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
public event PropertyChangedEventHandler PropertyChanged;
}
The using of that custom attribute with a property:
[PropertyChanged]
public string SomeProp { get; set; }
So basically I don't have to create full property for each field in the window, but only having simple property.
But for some reason, it won't work, and when debugging, the compiler don't even enter the custom attribute class.
Update
So after research on the subject, the attribute CallerMemberName
is processed in the compiler level, meaning, the compiler looking for that attribute and it itself pass the property/methods/etc... name to the method that use that attribute.
So basically, such thing isn't imposable to do without editing the compiler code and it's behavior.