StatusMessageViewModel.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 StatusMessageViewModel : ExtensionObjectViewModel 11 { 12 public ExtensionObject<IStatusMessage> Model { get; } 13 14 public string Message { get; private set; } = string.Empty; 15 16 public MessageState State { get; private set; } = MessageState.Info; 17 18 public ProgressViewModel? Progress { get; private set; } 19 20 public bool HasProgress => Progress is not null; 21 22 public StatusMessageViewModel(IStatusMessage message, WeakReference<IPageContext> context) 23 : base(context) 24 { 25 Model = new(message); 26 } 27 28 public override void InitializeProperties() 29 { 30 var model = Model.Unsafe; 31 if (model is null) 32 { 33 return; // throw? 34 } 35 36 Message = model.Message; 37 State = model.State; 38 var modelProgress = model.Progress; 39 if (modelProgress is not null) 40 { 41 Progress = new(modelProgress, this.PageContext); 42 Progress.InitializeProperties(); 43 UpdateProperty(nameof(HasProgress)); 44 } 45 46 model.PropChanged += Model_PropChanged; 47 } 48 49 private void Model_PropChanged(object sender, IPropChangedEventArgs args) 50 { 51 try 52 { 53 FetchProperty(args.PropertyName); 54 } 55 catch (Exception ex) 56 { 57 ShowException(ex); 58 } 59 } 60 61 protected virtual void FetchProperty(string propertyName) 62 { 63 var model = this.Model.Unsafe; 64 if (model is null) 65 { 66 return; // throw? 67 } 68 69 switch (propertyName) 70 { 71 case nameof(Message): 72 this.Message = model.Message; 73 break; 74 case nameof(State): 75 this.State = model.State; 76 break; 77 case nameof(Progress): 78 var modelProgress = model.Progress; 79 if (modelProgress is not null) 80 { 81 Progress = new(modelProgress, this.PageContext); 82 Progress.InitializeProperties(); 83 } 84 else 85 { 86 Progress = null; 87 } 88 89 UpdateProperty(nameof(HasProgress)); 90 break; 91 } 92 93 UpdateProperty(propertyName); 94 } 95 }