首页 > 解决方案 > 在 WPF 模型中发现用户偏好和更改的最佳方式

问题描述

想象一下PatientWPF 中的一个模型,其中一个属性是“温度”。现在,一位医生可能更喜欢摄氏温度,而另一位医生可能更喜欢华氏温度。如果当医生改变偏好时温度属性需要在 UI 中改变,我猜 Patient 的模型必须订阅一个事件。像这样的东西:

public Patient()
{
    Temperature.Instance.PropertyChanged += TemperatureChanged;
}
~Patient()
{
    Temperature.Instance.PropertyChanged -= TemperatureChanged;
}

但是,正如您可以推断的那样,虽然这可行,但我们正在使用Patient模型内的静态类进行订阅。有没有更优雅的方式来做到这一点?

即使Temperature该类在静态上下文中使用,我也担心模型不会取消订阅这些事件(我知道的唯一解决方案是在析构函数中)。并且它可能会导致应用程序运行时性能下降。这种担忧是真的吗?

我现在唯一的选择是在这样的偏好发生变化时要求重新加载视图......

标签: c#wpfmvvminotifypropertychanged

解决方案


“更改首选项”与设置属性相同。例如,您可以定义一个Units可以设置为Celsuisor的属性,Fahrenheit然后PropertyChanged为返回温度的属性引发事件,例如:

public class Patient : INotifyPropertyChanged
{
    private Units _units;
    public Units Units
    {
        get { return _units; }
        set
        {
            _units = value;
            NotifyPropertyChanged();
            NotifyPropertyChanged(nameof(FormattedTemperature));
        }
    }

    private double _temperature;
    public double Temperature
    {
        get { return _temperature; }
        set
        {
            _temperature = value;
            NotifyPropertyChanged();
            NotifyPropertyChanged(nameof(FormattedTemperature));
        }
    }

    public string FormattedTemperature =>
        _temperature.ToString() + (_units == Units.Celsuis ? " C" : " F");


    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] string propertyName = "") =>
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

public enum Units
{
    Celsuis,
    Fahrenheit
}

在您绑定到FormattedTemperature属性的视图中。

顺便说一句,实现一个取消订阅托管事件的终结器是没有意义的。


推荐阅读