DetailsLinkViewModel.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 CommunityToolkit.Mvvm.Input; 6 using Microsoft.CmdPal.Core.ViewModels.Models; 7 using Microsoft.CommandPalette.Extensions; 8 using Microsoft.CommandPalette.Extensions.Toolkit; 9 10 namespace Microsoft.CmdPal.Core.ViewModels; 11 12 public partial class DetailsLinkViewModel( 13 IDetailsElement _detailsElement, 14 WeakReference<IPageContext> context) : DetailsElementViewModel(_detailsElement, context) 15 { 16 private static readonly string[] _initProperties = [ 17 nameof(Text), 18 nameof(Link), 19 nameof(IsLink), 20 nameof(IsText), 21 nameof(NavigateCommand)]; 22 23 private readonly ExtensionObject<IDetailsLink> _dataModel = 24 new(_detailsElement.Data as IDetailsLink); 25 26 public string Text { get; private set; } = string.Empty; 27 28 public Uri? Link { get; private set; } 29 30 public bool IsLink => Link is not null; 31 32 public bool IsText => !IsLink; 33 34 public RelayCommand? NavigateCommand { get; private set; } 35 36 public override void InitializeProperties() 37 { 38 base.InitializeProperties(); 39 var model = _dataModel.Unsafe; 40 if (model is null) 41 { 42 return; 43 } 44 45 Text = model.Text ?? string.Empty; 46 Link = model.Link; 47 if (string.IsNullOrEmpty(Text) && Link is not null) 48 { 49 Text = Link.ToString(); 50 } 51 52 if (Link is not null) 53 { 54 // Custom command to open a link in the default browser or app, 55 // depending on the link type. 56 // Binding Link to a Hyperlink(Button).NavigateUri works only for 57 // certain URI schemes (e.g., http, https) and cannot open file: 58 // scheme URIs or local files. 59 NavigateCommand = new RelayCommand( 60 () => ShellHelpers.OpenInShell(Link.ToString()), 61 () => Link is not null); 62 } 63 64 UpdateProperty(_initProperties); 65 } 66 }