My WPF App receives a stream of messages from a backend service that I need to display in the UI. These messages vary widely and I want to have different visual layout (string formats, colors, Fonts, icons, whatever etc.) for each message.
I was hoping to just be able to create an inline (Run, TextBlock, Italic etc) for each message then somehow put them all in a ObservableCollection<>
and using he magic of WPF Data Binding on my TextBlock.Inlines in the UI. I couldn't find how to do this, is this possible?
TextBlock is not editable.
Text block is the primary control for displaying read-only text in apps. You can use it to display single-line or multi-line text, inline hyperlinks, and text with formatting like bold, italic, or underlined.
The TextBlock control provides flexible text support for UI scenarios that do not require more than one paragraph of text. It supports a number of properties that enable precise control of presentation, such as FontFamily, FontSize, FontWeight, TextEffects, and TextWrapping.
public class BindableTextBlock : TextBlock { public ObservableCollection<Inline> InlineList { get { return (ObservableCollection<Inline>)GetValue(InlineListProperty); } set { SetValue(InlineListProperty, value); } } public static readonly DependencyProperty InlineListProperty = DependencyProperty.Register("InlineList",typeof(ObservableCollection<Inline>), typeof(BindableTextBlock), new UIPropertyMetadata(null, OnPropertyChanged)); private static void OnPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { BindableTextBlock textBlock = sender as BindableTextBlock; ObservableCollection<Inline> list = e.NewValue as ObservableCollection<Inline>; list.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(textBlock.InlineCollectionChanged); } private void InlineCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add) { int idx = e.NewItems.Count -1; Inline inline = e.NewItems[idx] as Inline; this.Inlines.Add(inline); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With