获取电池信息reportUpdated MVVM窗口10

时间:2015-09-24 14:22:38

标签: c# mvvm uwp

As I can call reportUpdated event from my ViewModel?

<code>
        public MainPage() 
        { 
            this.InitializeComponent(); 
            Battery.AggregateBattery.ReportUpdated += AggregateBattery_ReportUpdated; 
        } 
 </code>

Here is a clear example of how to do this work. The problem is how to make this functionality but with a MVVM

2 个答案:

答案 0 :(得分:0)

几种选择......

  1. 将事件处理程序附加到VM中,而不是使用代码隐藏。编辑:正如评论中所指出的,这不是有史以来最干净的MVVM解决方案。更简洁的方法是在VM中使用某种独立于平台的接口(IAggregateBattery),并通过构造函数注入提供平台实现。
  2. 从AggregateBattery_ReportUpdated调用VM上的方法。
  3. 当事件发生时使用某种信使发送事件信息发送消息(MVVM Light有它,其他框架也可能这样做。)

答案 1 :(得分:0)

我找到了解决方案:

在构造函数中,我的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") + "%";
            }
        }