Files
Shrlalgo.RvKits/NeuWPF/NeoUI/Controls/SymbolIcon.xaml.cs
2025-08-20 12:10:13 +08:00

108 lines
3.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using NeumUI.Assets;
namespace NeumUI.Controls;
/// <summary>
/// Represents a text element containing an icon glyph.
/// </summary>
public sealed class SymbolIcon : Control
{
/// <summary>
/// 标识 <see cref="Symbol"/> 依赖属性
/// </summary>
public static readonly DependencyProperty SymbolProperty = DependencyProperty.Register(
nameof(Symbol),
typeof(MaterialSymbol),
typeof(SymbolIcon),
new PropertyMetadata(MaterialSymbol.Cr, OnGlyphChanged));
/// <summary>
/// 代表一个包含图标字形的文本元素。
/// </summary>
public SymbolIcon()
{
//重写 FontFamily 的默认值,指向你的字体库
//FontFamilyProperty.OverrideMetadata(typeof(SymbolIcon),
// new FrameworkPropertyMetadata(new FontFamily("pack://application:,,,/NeumUI;component/Assets/#Material Symbols Rounded")));
}
/// <summary>
/// 表示一个符号图标控件。
/// </summary>
/// <param name="symbol">要显示的符号。</param>
/// <param name="fontSize">符号的字体大小默认为14。</param>
public SymbolIcon(MaterialSymbol symbol, double fontSize = 14)
{
Symbol = symbol;
FontSize = fontSize;
}
private static void OnGlyphChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
//SetCurrentValue(GlyphProperty, Symbol.GetString());
// 将依赖对象转换为 SymbolIcon 实例
var control = (SymbolIcon)d;
// 在这里,你可以执行一些无法通过纯 XAML 绑定实现的逻辑。
// 例如:
// 1. 根据不同的图标触发不同的动画或视觉状态。
// 2. 记录或调试图标的变更。
// 3. 执行一些复杂的计算。
// 示例:假设我们有一个特殊的“同步”图标,当它被设置时,我们想触发一个动画。
// 这通常与 VisualStateManager 结合使用。
var newSymbol = (MaterialSymbol)e.NewValue;
if (newSymbol == MaterialSymbol.Sync) // 假设你的枚举中有 Sync
{
// 触发一个名为 "Syncing" 的视觉状态,该状态可以在 Generic.xaml 中定义一个旋转动画。
// VisualStateManager.GoToState(control, "Syncing", true);
}
else
{
// 回到普通状态
// VisualStateManager.GoToState(control, "Normal", true);
}
// 注意:因为我们已经在模板中通过数据绑定更新了 TextBlock 的 Text 属性,
// 所以这里不需要手动去查找模板中的 TextBlock 并设置其 Text。
// 数据绑定是处理这类UI更新的推荐方式。
}
/// <summary>
/// Gets or sets displayed <see cref="MaterialSymbol"/>.
/// </summary>
public MaterialSymbol Symbol
{
get => (MaterialSymbol)GetValue(SymbolProperty);
set => SetValue(SymbolProperty, value);
}
/// <summary>
/// 默认图标,当解析失败时使用。
/// </summary>
private const MaterialSymbol DefaultIcon = MaterialSymbol.Cr;
/// <summary>
/// Finds icon based on name.
/// </summary>
/// <param name="name">Name of the icon.</param>
public static MaterialSymbol Parse(string name)
{
if (string.IsNullOrEmpty(name))
{
return DefaultIcon;
}
try
{
return (MaterialSymbol)Enum.Parse(typeof(MaterialSymbol), name);
}
catch (Exception)
{
return DefaultIcon;
}
}
}