ProgressViewModel.cs
1 // Copyright (c) Microsoft Corporation 2 // The Microsoft Corporation licenses this file to you under the MIT license. 3 // See the LICENSE file in the project root for more information. 4 5 using Microsoft.CmdPal.Core.ViewModels.Models; 6 using Microsoft.CommandPalette.Extensions; 7 8 namespace Microsoft.CmdPal.Core.ViewModels; 9 10 public partial class ProgressViewModel : ExtensionObjectViewModel 11 { 12 public ExtensionObject<IProgressState> Model { get; } 13 14 public bool IsIndeterminate { get; private set; } 15 16 public uint ProgressPercent { get; private set; } 17 18 public ProgressViewModel(IProgressState progress, WeakReference<IPageContext> context) 19 : base(context) 20 { 21 Model = new(progress); 22 } 23 24 public override void InitializeProperties() 25 { 26 var model = Model.Unsafe; 27 if (model is null) 28 { 29 return; // throw? 30 } 31 32 IsIndeterminate = model.IsIndeterminate; 33 ProgressPercent = model.ProgressPercent; 34 35 model.PropChanged += Model_PropChanged; 36 } 37 38 private void Model_PropChanged(object sender, IPropChangedEventArgs args) 39 { 40 try 41 { 42 FetchProperty(args.PropertyName); 43 } 44 catch (Exception ex) 45 { 46 ShowException(ex); 47 } 48 } 49 50 protected virtual void FetchProperty(string propertyName) 51 { 52 var model = this.Model.Unsafe; 53 if (model is null) 54 { 55 return; // throw? 56 } 57 58 switch (propertyName) 59 { 60 case nameof(IsIndeterminate): 61 this.IsIndeterminate = model.IsIndeterminate; 62 break; 63 case nameof(ProgressPercent): 64 this.ProgressPercent = model.ProgressPercent; 65 break; 66 } 67 68 UpdateProperty(propertyName); 69 } 70 }