ContentIcon.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 System.Diagnostics; 6 using CommunityToolkit.WinUI; 7 using Microsoft.UI.Xaml; 8 using Microsoft.UI.Xaml.Controls; 9 10 namespace Microsoft.CmdPal.UI.Controls; 11 12 /// <summary> 13 /// A helper control which takes an <see cref="IconSource"/> and creates the corresponding <see cref="IconElement"/>. 14 /// </summary> 15 public partial class ContentIcon : FontIcon 16 { 17 public UIElement Content 18 { 19 get => (UIElement)GetValue(ContentProperty); 20 set => SetValue(ContentProperty, value); 21 } 22 23 public static readonly DependencyProperty ContentProperty = 24 DependencyProperty.Register( 25 nameof(Content), 26 typeof(UIElement), 27 typeof(ContentIcon), 28 new PropertyMetadata(null)); 29 30 public ContentIcon() 31 { 32 Loaded += IconBoxElement_Loaded; 33 } 34 35 private void IconBoxElement_Loaded(object sender, RoutedEventArgs e) 36 { 37 if (this.FindDescendants().OfType<Grid>().FirstOrDefault() is Grid grid && Content is not null) 38 { 39 if (grid.Children.Contains(Content)) 40 { 41 return; 42 } 43 44 if (Content is FrameworkElement element && element.Parent is not null) 45 { 46 Debug.Assert(false, $"IconBoxElement Content is already parented to {element.Parent.GetType().Name}"); 47 return; 48 } 49 50 grid.Children.Add(Content); 51 } 52 } 53 }