C# 属性绑定仍然是一样的吗?
我不是C# 属性绑定仍然是一样的吗?,c#,mvvm,C#,Mvvm,我不是XAML和MVVM专家。我想知道,经过所有最新的C#改进,我们是否仍然被迫编写MVVM属性,如下所示: private string sessionName; public string SessionName { get { return sessionName; } private set { sessionName = value; NotifyPropertyChanged(nameof(Se
XAML
和MVVM
专家。我想知道,经过所有最新的C#
改进,我们是否仍然被迫编写MVVM
属性,如下所示:
private string sessionName;
public string SessionName
{
get
{
return sessionName;
}
private set
{
sessionName = value;
NotifyPropertyChanged(nameof(SessionName));
}
}
public string SessionName { get; set; }
或者有更好的方法吗?您可以使用自动将引发PropertyChanged
事件的代码注入到编译时实现INotifyPropertyChanged
的类的属性设置器中
然后,您可以像这样实现您的属性:
private string sessionName;
public string SessionName
{
get
{
return sessionName;
}
private set
{
sessionName = value;
NotifyPropertyChanged(nameof(SessionName));
}
}
public string SessionName { get; set; }
C语言本身或UI框架中没有任何东西可以让您不用定义支持字段并在属性设置器中显式引发事件。即使您不打算走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);
}
}
好的建议,如果你打算使用Fody,我会确保你仔细阅读许可证。好的,仍然需要创建一个私有变量,然后是公共变量。