我正在使用Wpf,CaliburnMicro和mvvm模式构建一个小型个人项目。 该应用程序是一个触摸屏,可让用户查看室温并让他选择要在气候调节器上进行的命令(通风,冷,热,关),并显示该命令是否已从气候调节器“确认”。(反馈顺序)。来自Climatizer的数据来自串行通信。 我有一个ClimControlModel类,该类封装了RoomTemperature,Order和FeedBack Order等数据。
我已经简化了ClimControl类,因此代码在StackOverflow上不会占用太多行,而我只想在View中显示RoomTemperature。
ClimControlModel.cs:
namespace WpfMetroCaliburn.Models
{
public enum OrderValue
{
OFF,
VENT1,
VENT2,
VENT3,
COLD,
HOT,
OFFLINE
}
public class ClimControlModel
{
public float RoomTemperature { get; set; } = 99F; // fake value for testing
public OrderValue Order { get; set; }
public OrderValue FeedbackOrder { get; set; }
public ClimControlModel()
{
// will change val of RoomTemperature and FeedcackOrder every 5 seconds
ChangePropretiesPeriodically();
}
// this will simulate updating datas from Serial
public void ChangePropretiesPeriodically()
{
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnPropretiesChangeTimerEvent);
aTimer.Interval = 5000;
aTimer.Enabled = true;
}
// Assigning random values to RoomTemperature and Feedback Order for testing purposes
private void OnPropretiesChangeTimerEvent(object sender, ElapsedEventArgs e)
{
Array values = Enum.GetValues(typeof(OrderValue));
Random random = new Random();
FeedbackOrder = (OrderValue)values.GetValue(random.Next(values.Length));
Random rnd = new Random();
RoomTemperature = rnd.Next(20, 33);
Console.WriteLine($"FakeClimControlModel: RoomTemperature is now: {RoomTemperature}");
}
}
}
ShellViewModel:
namespace WpfMetroCaliburn.ViewModels
{
public class ShellViewModel : Screen
{
private ClimControlModel _clim;
public ClimControlModel Clim
{
get { return _clim; }
set {
_clim = value;
NotifyOfPropertyChange(() => Clim);
}
}
public ShellViewModel()
{
Clim = new ClimControlModel();
}
}
}
Xaml:
Window x:Class="WpfMetroCaliburn.Views.ShellView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfMetroCaliburn.Views"
mc:Ignorable="d"
Title="ShellView" Height="450" Width="800">
<Grid>
<TextBlock x:Name="Clim_RoomTemperature" FontSize="25"></TextBlock>
</Grid>
</Window>
我知道它不起作用,因为ClimControlModel实例实际上不会触发NotifyOfPropertyChange,因为对象本身不会更改,而是对象属性的值发生更改。 但是,在那种情况下,什么是“最佳实践”,就像我在ViewModel中创建RoomTemperature,Order,Feedback Order属性一样,如何在ViewModel中自动更改其值?
答案 0 :(得分:1)
随着模型属性的变化,视图注意到变化的唯一方法是模型实现INotifyPropertyChanged
并在属性变化时提高NotifyPropertyChanged
。
换句话说,对于模型中的每个属性,更改此样式:
public float RoomTemperature { get; set; }
到
private float roomTemperature;
public float RoomTemperature
{
get => this.roomTemperature;
set
{
this.roomTemperature=value;
this.NotifyPropertyChanged();
}
}
相反,如果您在ViewModel中添加了类似的属性,则在模型更改时不会收到通知。
另一种方法是让ViewModel订阅Timer事件,然后引发NotifyPropertyChanged
事件。