【问题标题】:How to catch changing of property in model by another property in ViewModel?如何通过 ViewModel 中的另一个属性捕捉模型中属性的变化?
【发布时间】:2018-04-26 19:01:04
【问题描述】:

我对模型的扩展有疑问。我需要在 Station 类中更新 AngleNegative 属性的同时更新 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,但之后有很多代码重复。

【问题讨论】:

    标签: c# wpf mvvm properties prism


    【解决方案1】:

    我会通过在 ViewModel 上设置一个方法来侦听其 Station 上的 PropertyChanged 事件,如下所示:

    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;
            }
        }
    }
    

    【讨论】:

    • 是的,好主意!我之前尝试过,但它不起作用,因为它必须订阅一组 Station 属性(我将对象链接到属性)。谢谢大佬!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    相关资源
    最近更新 更多