'Adding Inlines to TextBox is very slow

In my application i have a console-like-control that displays infromation I send from various functions using:

Run run = new Run("FancyText");
run.FontSize = 15;
run.FontFamily = new System.Windows.Media.FontFamily("Consolas");
run.Foreground = FancyColor;
tbConsole.Inlines.Add(run);
tbConsole.Inlines.Add(new LineBreak());

However this slows down my programm drastically after adding a lot of textboxes. Am i doing something wrong or is this just what you can expect? (By the way if i instead of the adding Runs to the Textbox i use a Stackpanel and add Textboxes it works fine and fast)



Solution 1:[1]

I have never been able to get this to run as fast as i wanted so i came up with a different approach which complies to MVVM. I created a virtualized stackpanel to contain textboxes that i create and add in code:

 <ScrollViewer Grid.Column="2" Name="consoleScroll" Background="Black">
    <ItemsControl  ItemsSource="{Binding Log}">
       <ItemsControl.ItemsPanel>
          <ItemsPanelTemplate>
             <VirtualizingStackPanel/>
          </ItemsPanelTemplate>
       </ItemsControl.ItemsPanel>
    </ItemsControl>
 </ScrollViewer>

Code:

public ObservableCollection<System.Windows.Controls.Control> Log
{
    get { return (ObservableCollection<System.Windows.Controls.Control>)this.GetValue(LogProperty); }
    set { this.SetValue(LogProperty, value); }
}

// Using a DependencyProperty as the backing store for Log.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty LogProperty =
    DependencyProperty.Register(nameof(Log), typeof(ObservableCollection<System.Windows.Controls.Control>), typeof(ViewModel), new PropertyMetadata(default(ObservableCollection<System.Windows.Controls.Control>)));

//Code to call in a function
TextBox tb = new TextBox();
tb.Foreground = new SolidColorBrush(Colors.Hotpink);
tb.HorizontalContentAlignment = HorizontalAlignment.Left;
tb.Text = "my nice string";
Log.Add(tb);

The resulting console window works as expected and supports multi color. Needed to censor parts of it... Resulting console window

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1