Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data binding the TextBlock.Inlines

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?

like image 685
will Avatar asked Dec 24 '09 21:12

will


People also ask

Is TextBlock editable?

TextBlock is not editable.

What is TextBlock?

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.

What is TextBlock WPF?

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.


1 Answers

You could add a Dependency Property to a TextBlock Subclass

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);         }     } } 
like image 79
Frank A. Avatar answered Oct 03 '22 14:10

Frank A.