/
FormattedString.cs
86 lines (70 loc) · 2.51 KB
/
FormattedString.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
namespace Xamarin.Forms
{
[ContentProperty("Spans")]
public class FormattedString : Element
{
readonly SpanCollection _spans = new SpanCollection();
internal event NotifyCollectionChangedEventHandler SpansCollectionChanged;
public FormattedString() => _spans.CollectionChanged += OnCollectionChanged;
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
for (int i = 0; i < Spans.Count; i++)
SetInheritedBindingContext(Spans[i], BindingContext);
}
public IList<Span> Spans => _spans;
public static explicit operator string(FormattedString formatted) => formatted.ToString();
public static implicit operator FormattedString(string text) => new FormattedString { Spans = { new Span { Text = text } } };
public override string ToString() => string.Concat(Spans.Select(span => span.Text));
void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (object item in e.OldItems)
{
var bo = item as Span;
bo.Parent = null;
if (bo != null)
{
bo.PropertyChanging -= OnItemPropertyChanging;
bo.PropertyChanged -= OnItemPropertyChanged;
}
}
}
if (e.NewItems != null)
{
foreach (object item in e.NewItems)
{
var bo = item as Span;
bo.Parent = this;
if (bo != null)
{
bo.PropertyChanging += OnItemPropertyChanging;
bo.PropertyChanged += OnItemPropertyChanged;
}
}
}
OnPropertyChanged(nameof(Spans));
SpansCollectionChanged?.Invoke(sender, e);
}
void OnItemPropertyChanged(object sender, PropertyChangedEventArgs e) => OnPropertyChanged(nameof(Spans));
void OnItemPropertyChanging(object sender, PropertyChangingEventArgs e) => OnPropertyChanging(nameof(Spans));
class SpanCollection : ObservableCollection<Span>
{
protected override void InsertItem(int index, Span item) => base.InsertItem(index, item ?? throw new ArgumentNullException(nameof(item)));
protected override void SetItem(int index, Span item) => base.SetItem(index, item ?? throw new ArgumentNullException(nameof(item)));
protected override void ClearItems()
{
var removed = new List<Span>(this);
base.ClearItems();
base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removed));
}
}
}
}