87 lines
3.0 KiB
C#
87 lines
3.0 KiB
C#
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 MelskinTest
|
|
{
|
|
public partial class ColorPaletteControl : UserControl
|
|
{
|
|
public List<ResourceItem> ColorResources { get; set; }
|
|
public List<ResourceItem> 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<ResourceItem>();
|
|
BrushResources = new List<ResourceItem>();
|
|
}
|
|
|
|
public IEnumerable<IGrouping<string, ResourceItem>> 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; }
|
|
}
|
|
}
|
|
} |