dotnet icon indicating copy to clipboard operation
dotnet copied to clipboard

Add attribute to declare `[ObservableProperty]` dependencies on dependent property

Open kaivol opened this issue 2 years ago • 0 comments

Overview

Declaring all dependent properties on the [ObservableProperty] can quickly become confusing. I think it would be easier/clearer if the dependencies could be declared using an attribute directly on the dependent property.

API breakdown

Possible attribute name: [DependsOn(...)]

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public sealed class DependsOnAttribute : Attribute
{ 
    public DependsOnAttribute(string propertyName)
    {
        PropertyNames = new[] { propertyName };
    }

    public DependsOnAttribute(string propertyName, params string[] otherPropertyNames)
    {
        PropertyNames = new[] { propertyName }.Concat(otherPropertyNames).ToArray();
    }

    public string[] PropertyNames { get; }
 }

Usage example

public sealed partial class PersonViewModel : ObservableObject
{
    [ObservableProperty]
    private string name;

    [ObservableProperty]
    private string surname;

    [DependsOn(nameof(Name), nameof(Surname))]
    public string FullName => $"{Name} {Surname}";
}
Generated code
public sealed partial class PersonViewModel
{
    public string Name
    {
        get => name;
        set
        {
            if (!global::System.Collections.Generic.EqualityComparer<string>.Default.Equals(name, value))
            {
                OnPropertyChanging();
                name = value;
                OnPropertyChanged();
                OnPropertyChanged("FullName");
            }
        }
    }

    public string Surname
    {
        get => surname;
        set
        {
            if (!global::System.Collections.Generic.EqualityComparer<string>.Default.Equals(surname, value))
            {
                OnPropertyChanging();
                surname = value;
                OnPropertyChanged();
                OnPropertyChanged("FullName");
            }
        }
    }
}

Breaking change?

No

Alternatives

Keep using [NotifyPropertyChangedFor]

Additional context

No response

Help us help you

Yes, I'd like to be assigned to work on this item

kaivol avatar Aug 11 '22 10:08 kaivol