Kiryuumaru / ObservableHelpers

Observable helpers with short-and-easy and UI-safe property implementations. Can be used for any MVVM software architectural applications.
MIT License
2 stars 0 forks source link

Question: Is there a way to still add code to a get or set of a property ? #2

Open BourgeoisDirk opened 1 year ago

BourgeoisDirk commented 1 year ago

No bug, just a question. It seems quite easy to use, but for instance with the example [ObservableProperty(Access = AccessModifier.PublicWithPrivateSetter)] string? family;

Is it somehow still possible to add code to the set of this property ? For instance some properties for a progressbar, int BarTotal & int BarPosition, I'd like to add code to the set property of BarTotal that is will set the BarPosition to 0; Is such a thing still possible with this Package ?

Kiryuumaru commented 1 year ago

Thank you for your question.

Currently, with the current version of the package, it is impossible to add code to the setter of the observable property. However, this feature can be considered for future updates to the package.

By including parameters such as OnGet, OnSetting, and OnSet, developers can define actions to be taken before and after the getter and setter methods are executed. For instance, in your specific scenario, OnSet could be used to set the BarPosition to 0 whenever the BarTotal property is updated.

It might look like this:

[ObservableProperty(
    Access = AccessModifier.PublicWithPrivateSetter),
    OnGet = OnGetFunction,
    OnSetting = OnSettingFunction, // before events
    OnSet = OnSetFunction // after events
] string? family;
Kiryuumaru commented 1 year ago

Or you could use NotifyPropertyChangedFor:

partial class MyViewModel : ObservableObject
{
    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(FullName))]
    private string name;

    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(FullName))]
    private string surname;

    public string FullName => $"{Name} {Surname}";
}

it may provide the desired functionality you are looking for

Kiryuumaru commented 1 year ago

Or this:


    [ObservableObject]
    public partial class Dinosaur
    {
        [ObservableProperty]
        string? name;

        [ObservableProperty(Access = Access.PublicWithPrivateSetter)]
        string? family;

        [ObservableProperty]
        int height;

        partial void OnFamilyChanged(bool value)
        {
            // your actions
            // will be executed after the value "family" changed and before the "OnPropertyChanged" event
        }
    }

All [ObservableProperty] has a corresponding partial method that can be optionally implemented.