56 lines
1.6 KiB
C#
56 lines
1.6 KiB
C#
using Avalonia.Data.Converters;
|
||
using Avalonia.Media;
|
||
using System;
|
||
using System.Collections.Generic;
|
||
using System.Globalization;
|
||
using System.Linq;
|
||
using System.Text;
|
||
using System.Threading.Tasks;
|
||
|
||
namespace Cowain.Base.Converters;
|
||
|
||
public class StringToBrushConverter : IValueConverter
|
||
{
|
||
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||
{
|
||
if (value is not string colorStr || string.IsNullOrWhiteSpace(colorStr))
|
||
{
|
||
// 默认颜色(透明/黑色)
|
||
return parameter?.ToString() == "Foreground"
|
||
? Brushes.Black
|
||
: Brushes.Transparent;
|
||
}
|
||
|
||
try
|
||
{
|
||
// 处理十六进制颜色(#FF0000 或 FF0000)
|
||
if (colorStr.StartsWith("#"))
|
||
{
|
||
return new SolidColorBrush(Color.Parse(colorStr));
|
||
}
|
||
// 处理命名颜色(Red/Green/Blue等)
|
||
else if (Color.TryParse(colorStr, out var color))
|
||
{
|
||
return new SolidColorBrush(color);
|
||
}
|
||
}
|
||
catch
|
||
{
|
||
// 转换失败返回默认色
|
||
return parameter?.ToString() == "Foreground"
|
||
? Brushes.Black
|
||
: Brushes.Transparent;
|
||
}
|
||
|
||
// 兜底默认色
|
||
return parameter?.ToString() == "Foreground"
|
||
? Brushes.Black
|
||
: Brushes.Transparent;
|
||
}
|
||
|
||
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||
{
|
||
throw new NotImplementedException();
|
||
}
|
||
}
|