[英]Updating several properties when another property changes?
在我的模型类中,我有几个列表和其他属性。 这些属性之一称为CurrentIteration
并且会不断更新。 更新后,我希望其他属性将自身更新为相应列表的元素,该列表是CurrentIteration
的索引。 我以为我需要包括的是一个要在CurrentIteration
设置器中更新的属性的OnPropertyChanged
事件。 但是,他们似乎没有被召集。
public class VehicleModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private List<double> _nowTime = new List<double>();
public List<double> NowTime
{
get { return this._nowTime; }
set { this._nowTime = value; OnPropertyChanged("Nowtime"); }
}
private List<double> _VehLat = new List<double>();
public List<double> VehLat
{
get { return this._VehLat; }
set { this._VehLat = value; OnPropertyChanged("VehLat"); }
}
private List<double> _VehLong = new List<double>();
public List<double> VehLong
{
get { return _VehLong; }
set { _VehLong = value; OnPropertyChanged("VehLong"); }
}
//non-list properties
private int _currentIteration;
public int CurrentIteration //used to hold current index of the list of data fields
{
get { return _currentIteration; }
set
{
_currentIteration = value;
OnPropertyChanged("CurrentIteration");
OnPropertyChanged("CurrentVehLat");
OnPropertyChanged("CurrentVehLong");
}
}
private double _currentVehLat;
public double CurrentVehLat
{
get { return _currentVehLat; }
set { _currentVehLat = VehLat[CurrentIteration]; OnPropertyChanged("CurrentVehLat"); }
}
private double _currentVehLong;
public double CurrentVehLong
{
get { return _currentVehLong; }
set { _currentVehLong = VehLong[CurrentIteration]; OnPropertyChanged("CurrentVehLong"); }
}
public void SetData(int i)
{
CurrentIteration = i;
}
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
CurrentIteration
确实得到正确更新,但其余部分则没有更新。 设置员被完全跳过。 我几乎肯定这很简单,在这种情况下我对二传手的理解是错误的,但是我不确定这到底是什么。
编辑:这是XAML中的绑定之一的示例:
Text="{Binding Path=CurrentVehLong,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}"
引发属性更改通知只是说“这些属性已更改,请重新查询其值”。 意味着它调用get
访问器方法。
看起来您期望它调用set
方法,但由于未设置值,因此不会发生。
尝试删除backing属性,然后直接访问数组值,如下所示:
public double CurrentVehLong
{
get { return VehLong[CurrentIteration];; }
set
{
VehLong[CurrentIteration] = value;
OnPropertyChanged("CurrentVehLong");
}
}
现在,当您调用OnPropertyChanged("CurrentVehLong")
,它将重新查询此属性的get
访问器,并基于CurrentIteration
更新该值。 我还更改了set
方法,使它更有意义,如果您要在其他地方执行此操作,则可以使用它来设置值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.