Files
WCS/Cowain.Base/Converters/StringToBrushConverter.cs
2026-03-02 09:08:20 +08:00

56 lines
1.6 KiB
C#
Raw Permalink 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 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();
}
}