获取电池信息报告更新MVVM窗口10
本文关键字:MVVM 窗口 更新 报告 信息 获取 | 更新日期: 2023-09-27 18:14:28
我可以从ViewModel中调用reportUpdated事件吗?
<code>
public MainPage()
{
this.InitializeComponent();
Battery.AggregateBattery.ReportUpdated += AggregateBattery_ReportUpdated;
}
</code>
这里有一个如何做这项工作的明确例子。问题是如何使用MVVM 实现此功能
几个选项。。。
- 将事件处理程序附加到VM内部,而不是使用代码隐藏。编辑:正如评论中所指出的,这不是有史以来最干净的MVVM解决方案。一个更干净的方法是在VM中拥有某种独立于平台的接口(IAggregateBattery(,并通过构造函数注入提供平台实现
- 从AggregateBattery_ReportUpdated调用VM上的方法
- 当事件发生时,使用某种信使发送带有事件信息的消息(MVVM Light有,其他框架可能也有(
我找到了解决方案:
在构造函数中我的ViewModel
<code>
public MainViewModel()
{
//The firs time, launch to method for get the current status battery
this.RequestAggregateBatteryReport();
// This event is launch each time, when the status battery change
Battery.AggregateBattery.ReportUpdated += AggregateBattery_ReportUpdated1;
}
private async void AggregateBattery_ReportUpdated1(Battery sender, object args)
{
//The Dispatcher is used when in other thread because is important use the other thread for avoid issue.
Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
RequestAggregateBatteryReport();
});
}
private void RequestAggregateBatteryReport()
{
// Create aggregate battery object
var aggBattery = Battery.AggregateBattery;
// Get report
var report = aggBattery.GetReport();
// Update UI
AddReportUI(report, aggBattery.DeviceId);
}
private void AddReportUI(BatteryReport report, string DeviceID)
{
this.BatteryEnergy = new BatteryEnergy();
// Disable progress bar if values are null
if ((report.FullChargeCapacityInMilliwattHours == null) ||
(report.RemainingCapacityInMilliwattHours == null))
{
this.BatteryEnergy.ProgressBarMaxium = 0.0;
this.BatteryEnergy.ProgressBarValue = 0.0;
this.BatteryEnergy.ProgressBarPorcent = "N/A";
}
else
{
this.BatteryEnergy.ProgressBarMaxium = Convert.ToDouble(report.FullChargeCapacityInMilliwattHours);
this.BatteryEnergy.ProgressBarValue = Convert.ToDouble(report.RemainingCapacityInMilliwattHours);
this.BatteryEnergy.ProgressBarPorcent = ((Convert.ToDouble(report.RemainingCapacityInMilliwattHours) / Convert.ToDouble(report.FullChargeCapacityInMilliwattHours)) * 100).ToString("F2") + "%";
}
}