/ src / modules / cmdpal / Microsoft.CmdPal.UI.ViewModels / ContentMarkdownViewModel.cs
ContentMarkdownViewModel.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;
 6  using Microsoft.CmdPal.Core.ViewModels.Models;
 7  using Microsoft.CommandPalette.Extensions;
 8  
 9  namespace Microsoft.CmdPal.UI.ViewModels;
10  
11  public partial class ContentMarkdownViewModel(IMarkdownContent _markdown, WeakReference<IPageContext> context) :
12      ContentViewModel(context)
13  {
14      public ExtensionObject<IMarkdownContent> Model { get; } = new(_markdown);
15  
16      // Remember - "observable" properties from the model (via PropChanged)
17      // cannot be marked [ObservableProperty]
18      public string Body { get; protected set; } = string.Empty;
19  
20      public override void InitializeProperties()
21      {
22          var model = Model.Unsafe;
23          if (model is null)
24          {
25              return;
26          }
27  
28          Body = model.Body;
29          UpdateProperty(nameof(Body));
30  
31          model.PropChanged += Model_PropChanged;
32      }
33  
34      private void Model_PropChanged(object sender, IPropChangedEventArgs args)
35      {
36          try
37          {
38              var propName = args.PropertyName;
39              FetchProperty(propName);
40          }
41          catch (Exception ex)
42          {
43              ShowException(ex);
44          }
45      }
46  
47      protected void FetchProperty(string propertyName)
48      {
49          var model = Model.Unsafe;
50          if (model is null)
51          {
52              return; // throw?
53          }
54  
55          switch (propertyName)
56          {
57              case nameof(Body):
58                  Body = model.Body;
59                  break;
60          }
61  
62          UpdateProperty(propertyName);
63      }
64  
65      protected override void UnsafeCleanup()
66      {
67          base.UnsafeCleanup();
68          var model = Model.Unsafe;
69          if (model is not null)
70          {
71              model.PropChanged -= Model_PropChanged;
72          }
73      }
74  }