-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
DecorableTextElement.cs
65 lines (54 loc) · 2.45 KB
/
DecorableTextElement.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#nullable disable
using System;
using System.ComponentModel;
using System.Globalization;
namespace Microsoft.Maui.Controls
{
static class DecorableTextElement
{
/// <summary>Bindable property for <see cref="TextDecorations"/>.</summary>
public static readonly BindableProperty TextDecorationsProperty = BindableProperty.Create(nameof(IDecorableTextElement.TextDecorations), typeof(TextDecorations), typeof(IDecorableTextElement), TextDecorations.None);
}
/// <include file="../../docs/Microsoft.Maui.Controls/TextDecorationConverter.xml" path="Type[@FullName='Microsoft.Maui.Controls.TextDecorationConverter']/Docs/*" />
public class TextDecorationConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
=> sourceType == typeof(string);
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
=> destinationType == typeof(string);
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
var strValue = value?.ToString();
TextDecorations result = TextDecorations.None;
if (strValue == null)
throw new InvalidOperationException(string.Format("Cannot convert \"{0}\" into {1}", strValue, typeof(TextDecorations)));
var valueArr = strValue.Split(',');
if (valueArr.Length <= 1)
valueArr = strValue.Split(' ');
foreach (var item in valueArr)
{
if (Enum.TryParse(item.Trim(), true, out TextDecorations textDecorations))
result |= textDecorations;
else if (item.Equals("line-through", StringComparison.OrdinalIgnoreCase))
result |= TextDecorations.Strikethrough;
else
throw new InvalidOperationException(string.Format("Cannot convert \"{0}\" into {1}", item, typeof(TextDecorations)));
}
return result;
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (value is not TextDecorations td)
throw new NotSupportedException();
if (td == TextDecorations.None)
return nameof(TextDecorations.None);
if (td == TextDecorations.Underline)
return nameof(TextDecorations.Underline);
if (td == TextDecorations.Strikethrough)
return nameof(TextDecorations.Strikethrough);
if (td == (TextDecorations.Underline & TextDecorations.Strikethrough))
return $"{nameof(TextDecorations.Underline)}, {nameof(TextDecorations.Strikethrough)}";
throw new NotSupportedException();
}
}
}