[英]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.