我知道这是一个老问题,但这是“NotifyPropertyChanged of linked properties”在谷歌中的第一条搜索结果,所以我认为添加这个答案是合适的,以便提供一些具体的代码。
我使用了Robert Rossney的建议,并创建了一个自定义属性,然后在基视图模型的PropertyChanged事件中使用它。
属性类:
[AttributeUsage(AttributeTargets.Property,AllowMultiple = true)]
public class DependsOnPropertyAttribute : Attribute
{
public readonly string Dependence;
public DependsOnPropertyAttribute(string otherProperty)
{
Dependence = otherProperty;
}
}
而在我的基本视图模型中(所有其他 WPF 视图模型都继承自此):
public abstract class BaseViewModel : INotifyPropertyChanged
{
protected Dictionary<string, List<string>> DependencyMap;
protected BaseViewModel()
{
DependencyMap = new Dictionary<string, List<string>>();
foreach (var property in GetType().GetProperties())
{
var attributes = property.GetCustomAttributes<DependsOnPropertyAttribute>();
foreach (var dependsAttr in attributes)
{
if (dependsAttr == null)
continue;
var dependence = dependsAttr.Dependence;
if (!DependencyMap.ContainsKey(dependence))
DependencyMap.Add(dependence, new List<string>());
DependencyMap[dependence].Add(property.Name);
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler == null)
return;
handler(this, new PropertyChangedEventArgs(propertyName));
if (!DependencyMap.ContainsKey(propertyName))
return;
foreach (var dependentProperty in DependencyMap[propertyName])
{
handler(this, new PropertyChangedEventArgs(dependentProperty));
}
}
}
现在我可以轻松地标记属性,就像这样:
public int NormalProperty
{
get {return _model.modelProperty; }
set
{
_model.modelProperty = value;
OnPropertyChanged();
}
}
[DependsOnProperty(nameof(NormalProperty))]
public int CalculatedProperty
{
get { return _model.modelProperty + 1; }
}