using System.Collections.Specialized; using System.Windows.Documents; namespace QuikDawEditor.EDITING.MiscClasses; public class BindableTextBlock : TextBlock { public ObservableCollection InlineList { get { return (ObservableCollection)GetValue(InlineListProperty); } set { SetValue(InlineListProperty, value); } } public static readonly DependencyProperty InlineListProperty = DependencyProperty.Register("InlineList", typeof(ObservableCollection), typeof(BindableTextBlock), new UIPropertyMetadata(null, OnPropertyChanged)); private static void OnPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { BindableTextBlock textBlock = (BindableTextBlock)sender; // subscribe to collection changed textBlock.UpdateInlineListSource((ObservableCollection)e.OldValue, (ObservableCollection)e.NewValue); } public void UpdateInlineListSource(ObservableCollection oldCollection, ObservableCollection newCollection) { if (oldCollection != null) oldCollection.CollectionChanged -= OnCollectionChanged; if (newCollection != null) { newCollection.CollectionChanged += OnCollectionChanged; OnCollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); OnCollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, newCollection)); } } private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { var newItems = e.NewItems?.Cast()?.ToList() ?? new List(); var oldItems = e.OldItems?.Cast()?.ToList() ?? new List(); // changed source if (e.Action == NotifyCollectionChangedAction.Reset) Inlines.Clear(); foreach (var itemForDelete in oldItems.ToList()) { if (Inlines.Contains(itemForDelete)) Inlines.Remove(itemForDelete); } foreach (var itemsForAdd in newItems) { Inlines.Add(itemsForAdd); } } }