有没有一种方法可以简化ViewModels中的属性定义?

时间:2019-07-05 14:39:08

标签: c# xamarin xamarin.forms

我有很多看起来像这样的属性:

string _aBtnState;
public string ABtnState { get => _aBtnState; set => SetProperty(ref _aBtnState, value); }

这是我使用的SetProperty方法:

public class ObservableObject : INotifyPropertyChanged
{

    protected virtual bool SetProperty<T>(
        ref T backingStore, T value,
        [CallerMemberName]string propertyName = "",
        Action onChanged = null)
    {
        if (EqualityComparer<T>.Default.Equals(backingStore, value))
            return false;

        backingStore = value;
        onChanged?.Invoke();
        OnPropertyChanged(propertyName);
        return true;
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = "") =>
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

}

有没有办法将其简化为以下形式:

public object ABtnState { get; set; }

或者也许

SetMyProperty(ABtnState);

,并且仍然具有相同的功能。

1 个答案:

答案 0 :(得分:1)

我认为没有比这更简单的方法了。我建议您在Visual Studio中创建一个片段以加快该过程。

private $type$ $field$;

public $type$ $property$
{
    get => this.$field$;
    set => this.SetValue(ref this.$field$, value);
}

VSCode

https://code.visualstudio.com/docs/editor/userdefinedsnippets

VS Mac

https://docs.microsoft.com/en-us/visualstudio/mac/snippets?view=vsmac-2019

VS Windows

https://docs.microsoft.com/en-us/visualstudio/ide/walkthrough-creating-a-code-snippet?view=vs-2019