原來我寫了個基類
public class VMBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
然后具體實作一般是這樣子的
public class VMTest:VMBase
{
private string _Test;
public string Test
{
get => _Test;
set
{
_Test = value;
RaisePropertyChanged();
}
}
}
每次寫起來特別不爽,今天折騰了個新的基類,稍許簡單點
public class VMBase : INotifyPropertyChanged
{
private readonly Dictionary<string, object> CDField = new Dictionary<string, object>();
public event PropertyChangedEventHandler PropertyChanged;
public T G<T>([CallerMemberName] string propertyName = "")
{
object _propertyValue;
if (!CDField.TryGetValue(propertyName, out _propertyValue))
{
_propertyValue = https://www.cnblogs.com/catzhou/archive/2020/09/23/default(T);
CDField.Add(propertyName, _propertyValue);
}
return (T)_propertyValue;
}
public void V(object value, [CallerMemberName] string propertyName ="")
{
if (!CDField.ContainsKey(propertyName) || CDField[propertyName] != (object)value)
{
CDField[propertyName] = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
具體實作就變成這個樣子了
public class VMTest:VMBase
{
public string Test
{
get => G<string>();
set => V(value);
}
}
只能說稍許簡單點,不知道還有沒有更方便的寫法,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/114325.html
標籤:.NET技术
