我的问题似乎是“范围”,尽管我不确定这是正确的术语。我想在设置自定义对象中的属性时通知只读列表重新评估自身。我相信它根本不知道它的存在。也许有一个简单的方法可以解决这个问题,我想不出,但我正在画一个空白。
我发现这很难用语言表达,因此这里是简化的代码,其中包含我对预期发生的情况的评论。
我要绑定(bind)数据的对象内的属性:
private CvarAspectRatios _aspectRatio = new CvarAspectRatios("none", GetRatio());
public CvarAspectRatios AspectRatio
{
get { return _aspectRatio; }
set
{ // This setter never gets hit since I bind to this
if (value != null) // object's 'Value' property now.
{
_aspectRatio = value;
NotifyPropertyChanged("AspectRatio");
NotifyPropertyChanged("ResolutionList"); // I want to inform ResolutionList
} // that it needs to repopulate based
} // on this property: AspectRatio
}
private ResolutionCollection _resolutionList = ResolutionCollection.GetResolutionCollection();
public ResolutionCollection ResolutionList
{
get
{
ResolutionCollection list = new ResolutionCollection();
if (AspectRatio != null && AspectRatio.Value != null)
{
foreach (Resolutions res in _resolutionList.Where(i => i.Compatibility == AspectRatio.Value.Compatibility))
{
list.Add(res);
}
return list;
}
return _resolutionList;
}
}
CvarAspectRatios 类:
public class CVarAspectRatios : INotifyPropertyChanged
{
private string _defaultValue;
public string DefaultValue
{
get { return _defaultValue; }
set { _defaultValue = value; NotifyPropertyChanged("DefaultValue"); }
}
private AspectRatios _value;
public AspectRatios Value
{
get { return _value; }
set
{
_value = value;
NotifyPropertyChanged("Value");
NotifyPropertyChanged("ResolutionList"); // This value gets set, and I'd like for ResolutionList to update
} // but it cannot find ResolutionList. No errors or anything. Just
} // no update.
public AspectRatios() { }
public AspectRatios(string defaultValue, AspectRatios val)
{
DefaultValue = defaultValue;
Value = val;
}
// Implementation of INotifyPropertyChanged snipped out here
}
大家觉得怎么样?如果您想要一个示例应用程序,我可以制作一个。
最佳答案
由于 CVarAspectRatios 实现了 INotifyPropertyChanged,因此您可以让 viewmodel 类订阅 AspectRatio 的 PropertyChanged 事件。
public class YourViewModel
{
public YourViewModel()
{
AspectRatio.PropertyChanged += AspectRatio_PropertyChanged;
}
void AspectRatio_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Value")
NotifyPropertyChanged("ResolutionList");
}
}
请记住,如果您丢弃该 AspectRatio 对象(如果对象引用发生变化,而不仅仅是该对象的 value 属性发生变化),您应该取消订阅被丢弃的对象上的事件。
关于c# - 如何在类中的类的属性上使用 INotifyPropertyChanged..?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6155381/