首页 > 解决方案 > 将内联添加到 TextBox 非常慢

问题描述

在我的应用程序中,我有一个类似控制台的控件,它显示我从各种功能发送的输出,使用:

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());

然而,这大大减慢了我的程序......我做错了什么还是这正是你所期望的?(顺便说一句,如果我不是将运行添加到文本框,而是使用 Stackpanel 并添加文本框,它可以正常工作且快速)

标签: c#wpf

解决方案


我从来没有能够让它以我想要的速度运行,所以我想出了一种符合 MVVM 的不同方法。我创建了一个虚拟化堆栈面板来包含我在代码中创建和添加的文本框:

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

代码:

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);

生成的控制台窗口按预期工作并支持多色。需要审查它的一部分... 生成的控制台窗口


推荐阅读