c# - 将内联添加到 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 并添加文本框,它可以正常工作且快速)
解决方案
我从来没有能够让它以我想要的速度运行,所以我想出了一种符合 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);
推荐阅读
- ios - 错误 - 顶层不允许使用表达式
- android - Android Firebase 获取数据库中的最后一个按键
- python - Python中的嵌套积分
- jena - 为什么 SHACL API 的 SHShape.hasTargetNode 对目标类返回 False?
- python - 在有序列表中选择 N 个变化点
- google-dfp - Prebid.js DFP 它们如何协同工作
- python - 无法从图表中打印每首歌曲的标题。获取属性错误?
- javascript - 是否可以使用“with”模板标签从 Django 模板中使用 JavaScript 生成的文本
- angular - 带有排序,分页和过滤页面问题的角度材料数据表
- sql - 如何在 SQL 中查询多条链接记录以返回一行