如何通过ViewModel中的另一个属性捕获模型中的属性更改?

时间:2017-11-13 23:53:52

标签: c# wpf mvvm properties prism

我对模型的扩展有问题。我需要在Station类中更新属性Angle的同时更新AngleNegative属性。 AngleNegative属性数据基于Angle中的数据,如示例所示。我无法修改Station模型,因为它在另一个VM中使用并且具有相同的问题但具有其他属性。这可以是什么解决方案?

  public class Station : BindableBase, IStation
     {
        //some properties
        .
        .
        .

        private int _angle;

        public int Angle
        {
            get => _angle;
            set => SetProperty(ref _angle, value);
        }
     }


public class ViewModel : BindableBase
    {
        private Station _station;
        public Station Station
        {
            get => _station;
            set => SetProperty(ref _station, value);
        }

        //delete this property duplicate and base on Station.Angle
        private int _angle;
        public int Angle
        {
            get => _angle;
            set
            {
                SetProperty(ref _angle, value);
                AngleNegative = value - 180;
            }
        }

        private int _angleNegative;

        public int AngleNegative
        {
            get => _angleNegative;
            set => SetProperty(ref _angleNegative, value);
        }
    }

我认为我可以从IStation继承VM,但是很多代码在之后重复。

1 个答案:

答案 0 :(得分:0)

我会通过在ViewModel上监听PropertyChanged上的Station事件的方法来实现,如下所示:

public class ViewModel : BindableBase
{
    private Station _station;
    public Station Station
    {
        get => _station;
        set => SetProperty(ref _station, value);
    }

    private int _angleNegative;
    public int AngleNegative
    {
        get => _angleNegative;
        set => SetProperty(ref _angleNegative, value);
    }

    public ViewModel()
    {
        Station.PropertyChanged += Station_PropertyChanged;
    }

    private void Station_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "Angle")
        {
            AngleNegative = Station.Angle - 180;
        }
    }
}