属性绑定仍然一样吗?

时间:2019-08-28 14:55:37

标签: c# mvvm

我不是XAMLMVVM专家。我想知道,是否通过所有最新的C#改进,仍然被迫像这样编写我们的MVVM属性:

private string sessionName;

public string SessionName
{
    get
    {
        return sessionName;
    }
    private set
    {
        sessionName = value;
        NotifyPropertyChanged(nameof(SessionName));
    }
}

还是有更好的方法呢?

2 个答案:

答案 0 :(得分:1)

您可以使用Fody自动将引发PropertyChanged事件的代码注入到在编译时实现INotifyPropertyChanged的类的属性设置器中。

然后您可以像这样实现您的属性:

public string SessionName { get; set; }

尽管C#语言本身或UI框架中没有任何东西可以使您不必定义后备字段并在属性设置器中显式引发事件。

答案 1 :(得分:0)

即使您不打算采用Fody路线,仍然可以从MVVM属性定义中删除很多冗长的词。

为模型/视图模型提供基类

/// <summary>
/// Base class that implements INotifyPropertyChanged
/// </summary>
public abstract class BindableBase: INotifyPropertyChanged
{
    // INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    // update a property value, and fire PropertyChanged event when the value is actually updated
    protected bool Set<T>(string propertyName, ref T field, T newValue)
    {
        if (EqualityComparer<T>.Default.Equals(field, newValue))
            return false;

        field = newValue;
        RaisePropertyChanged(propertyName);
        return true;
    }

    // update a property value, and fire PropertyChanged event when the value is actually updated
    // without having to pass in the property name
    protected bool Set<T>(ref T field, T newValue, [CallerMemberName]string propertyName = null)
    {
        return Set(propertyName, ref field, newValue);
    }
}

您现在可以将属性定义写为

public class Session: BindableBase
{
    private string sessionName;

    public string SessionName
    {
        get => sessionName;
        private set => Set(ref sessionName, value);
     }
}