using System; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Controls.Primitives; using Microsoft.UI.Xaml.Media; using Microsoft.UI.Xaml.Media.Imaging; namespace Sonex.Client.Controls; public sealed class ToolBarToggleButton : ToggleButton { public static readonly DependencyProperty IconSourceProperty = DependencyProperty.Register( nameof(IconSource), typeof(string), typeof(ToolBarToggleButton), new PropertyMetadata(string.Empty, OnIconSourceChanged)); private readonly Image _iconImage = new() { Width = 18, Height = 18, Stretch = Stretch.Uniform, UseLayoutRounding = true }; private bool _iconManagedContent; public ToolBarToggleButton() { MinWidth = 32; Width = 32; Height = 32; Padding = new Thickness(6); CornerRadius = new CornerRadius(4); BorderThickness = new Thickness(1); UseSystemFocusVisuals = false; FocusVisualPrimaryThickness = new Thickness(0); FocusVisualSecondaryThickness = new Thickness(0); HorizontalAlignment = HorizontalAlignment.Center; VerticalAlignment = VerticalAlignment.Center; Transitions = null; UseLayoutRounding = true; UpdateIconContent(IconSource); } public string IconSource { get => (string)GetValue(IconSourceProperty); set => SetValue(IconSourceProperty, value); } private static void OnIconSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is ToolBarToggleButton control) { control.UpdateIconContent(e.NewValue as string); } } private void UpdateIconContent(string? source) { if (string.IsNullOrWhiteSpace(source)) { if (_iconManagedContent) { Content = null; _iconManagedContent = false; } return; } var imageSource = CreateImageSource(source); if (imageSource == null) { return; } _iconImage.Source = imageSource; Content = _iconImage; _iconManagedContent = true; } private static ImageSource? CreateImageSource(string source) { if (!TryCreateUri(source, out var uri)) { return null; } if (source.Trim().EndsWith(".svg", StringComparison.OrdinalIgnoreCase)) { return new SvgImageSource(uri) { RasterizePixelWidth = 18, RasterizePixelHeight = 18 }; } return new BitmapImage(uri); } private static bool TryCreateUri(string source, out Uri uri) { uri = null!; var normalized = source.Trim(); if (Uri.TryCreate(normalized, UriKind.Absolute, out var absoluteUri) && absoluteUri is not null) { uri = absoluteUri; return true; } if (Uri.TryCreate($"ms-appx:///{normalized.TrimStart('/')}", UriKind.Absolute, out var appxUri) && appxUri is not null) { uri = appxUri; return true; } return false; } }