另一个属性更改时更新多个属性?

时间:2016-12-08 18:02:57

标签: c# wpf mvvm properties

在我的模型类中,我有几个列表和其他属性。其中一个属性称为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}"

1 个答案:

答案 0 :(得分:2)

提升属性更改通知只是说“这些属性已更改,重新查询其值”。这意味着它调用get访问器方法。

看起来你期望它调用set方法,因为你没有设置值,所以不会发生这种情况。

尝试删除backing属性并直接访问数组值,如下所示:

public double CurrentVehLong
{
    get { return VehLong[CurrentIteration];; }
    set 
    { 
        VehLong[CurrentIteration] = value; 
        OnPropertyChanged("CurrentVehLong"); 
    }
}

现在,当您致电OnPropertyChanged("CurrentVehLong")时,它会重新查询此属性的get访问者,并根据CurrentIteration更新值。我还改变了set方法,因此它更有意义,如果你想在其他地方做什么,你就可以用它来设置值。

相关问题