c# - 在 WPF 模型中发现用户偏好和更改的最佳方式
问题描述
想象一下Patient
WPF 中的一个模型,其中一个属性是“温度”。现在,一位医生可能更喜欢摄氏温度,而另一位医生可能更喜欢华氏温度。如果当医生改变偏好时温度属性需要在 UI 中改变,我猜 Patient 的模型必须订阅一个事件。像这样的东西:
public Patient()
{
Temperature.Instance.PropertyChanged += TemperatureChanged;
}
~Patient()
{
Temperature.Instance.PropertyChanged -= TemperatureChanged;
}
但是,正如您可以推断的那样,虽然这可行,但我们正在使用Patient
模型内的静态类进行订阅。有没有更优雅的方式来做到这一点?
即使Temperature
该类在静态上下文中使用,我也担心模型不会取消订阅这些事件(我知道的唯一解决方案是在析构函数中)。并且它可能会导致应用程序运行时性能下降。这种担忧是真的吗?
我现在唯一的选择是在这样的偏好发生变化时要求重新加载视图......
解决方案
“更改首选项”与设置属性相同。例如,您可以定义一个Units
可以设置为Celsuis
or的属性,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
属性的视图中。
顺便说一句,实现一个取消订阅托管事件的终结器是没有意义的。
推荐阅读
- javascript - 如果用户没有向上滚动,则在 js 中滚动元素
- php - 请帮助我使用函数 mail() 将表单的内容发送到我的邮件
- r - 在一组变量中为每个唯一的人找到第一个非缺失值,然后在该点之后将所有 NA 更改为 0
- python - Tkinter - 事件队列和事件顺序
- .htaccess - htaccess 非 www 不重定向
- cmake - 如何阻止 CLion 将额外选项传递给 cmake
- amazon-web-services - 通过 Glue 将数据插入 Redshift 时出现“找不到分隔符”错误
- apache-kafka - Producer clientId=producer-1 Bootstrap broker localhost:9092 (id: -1 rack: null) 断开连接 - Spring Boot Kafka
- sql - sql - INSTEAD OF INSERT 触发器 - 插入前清除值
- c# - Akka.NET FSM - 测试 OnTermination 转换