【发布时间】:2017-04-24 01:53:44
【问题描述】:
在我的模型类中,我有几个列表和其他属性。其中一个属性称为CurrentIteration,并且会不断更新。当它被更新时,我希望其他属性将自己更新为相应列表的元素,即CurrentIteration 的索引。我认为我需要包含的只是一个OnPropertyChanged 事件,用于我想在CurrentIteration 的设置器中更新的属性。但是,他们似乎没有被调用。
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}"
【问题讨论】:
-
您好,您是否介意展示一下 xaml 中的数据绑定对于那些非更新属性如何? - 谢谢
-
好的,将它添加到帖子的末尾。
-
一种选择是简单地将
OnPropertyChanged("CurrentVehLat"); OnPropertyChanged("CurrentVehLong");中的CurrentIteration设置器替换为对其他设置器的调用(它们将调用它们自己的 OnPropertyChanged):CurrentVehLat = double.MaxValue;,CurrentVehLong = double.MinValue;(值不'没关系,你从来没有在那些 setter 中读过value)。通过这种方式,任何时候 CurrentIteration 被分配,他的 setter 都会调用另一个属性的 setter 来获取更新的CurrentIteration值。
标签: c# wpf mvvm properties