using System.Collections.Generic; using System.Collections.ObjectModel; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; namespace ChatController.Core { public class OwnChatRichTextBox : RichTextBox { public ObservableCollection InlineList { get => (ObservableCollection)GetValue(InlineListProperty); set => SetValue(InlineListProperty, value); } public static readonly DependencyProperty InlineListProperty = DependencyProperty.Register("InlineList", typeof(ObservableCollection), typeof(OwnChatRichTextBox), new UIPropertyMetadata(null, OnPropertyChanged)); public static void OnPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { if (e.NewValue is null) { return; } ((OwnChatRichTextBox)sender).Document = GetCustomDocument(e.NewValue as ObservableCollection); if(sender is OwnChatRichTextBox ownChatRichTextBox) { ownChatRichTextBox.Document = GetCustomDocument(e.NewValue as ObservableCollection); ownChatRichTextBox.Width = ownChatRichTextBox.Document.GetFormattedText().WidthIncludingTrailingWhitespace + 20; } } private static FlowDocument GetCustomDocument(IEnumerable inlines) { var flowDocument = new FlowDocument(); var paragraph = new Paragraph { Margin = new Thickness(0) }; paragraph.Inlines.AddRange(inlines); flowDocument.Blocks.Add(paragraph); return flowDocument; } } }