using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace VariaStudioTest { public partial class ColorPaletteControl : UserControl { public List ColorResources { get; set; } public List BrushResources { get; set; } public static readonly DependencyProperty SourceUriProperty = DependencyProperty.Register(nameof(SourceUri), typeof(string), typeof(ColorPaletteControl), new PropertyMetadata(null, OnSourceUriChanged)); public string SourceUri { get { return (string)GetValue(SourceUriProperty); } set { SetValue(SourceUriProperty, value); } } private static void OnSourceUriChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ColorPaletteControl control = (ColorPaletteControl)d; string uriString = (string)e.NewValue; if (!string.IsNullOrEmpty(uriString)) { control.LoadResources(new Uri(uriString, UriKind.RelativeOrAbsolute)); } } private void LoadResources(Uri uri) { var resourceDictionary = new ResourceDictionary { Source = uri }; ColorResources.Clear(); BrushResources.Clear(); foreach (DictionaryEntry entry in resourceDictionary) { string key = entry.Key.ToString(); // 用正则分割驼峰或 Pascal 命名,取第一个单词 var match = Regex.Match(key, @"^[A-Z][a-z]*"); string prefix = match.Success ? match.Value : key; if (entry.Value is Color color) { ColorResources.Add(new ResourceItem { Key = entry.Key.ToString(), Prefix = prefix, Value = new SolidColorBrush(color) }); } else if (entry.Value is SolidColorBrush brush) { BrushResources.Add(new ResourceItem { Key = key, Value = brush, Prefix = prefix }); } } ColorResources = ColorResources.OrderBy(c => c.Key).ToList(); BrushResources = BrushResources.OrderBy(c => c.Key).ToList(); DataContext = this; } public ColorPaletteControl() { InitializeComponent(); ColorResources = new List(); BrushResources = new List(); } public IEnumerable> GroupedBrushResources { get { return BrushResources.GroupBy(b => b.Prefix); } } public class ResourceItem { public string Key { get; set; } public SolidColorBrush Value { get; set; } public string Prefix { get; set; } } } }