gpt4 book ai didi

c# - WPF DataGrid 和多线程

转载 作者:行者123 更新时间:2023-11-30 16:23:55 25 4
gpt4 key购买 nike

我有一个用 DataView 填充的 DataGrid(使用 DataContext)。我试图在一个单独的线程中执行此操作,但 UI 仍然卡住。我想防止 UI 在填充 DataGrid 时卡住。

这是我到目前为止编写的代码:

private void btnOK_Click(object sender, RoutedEventArgs e)
{
GetFieldsBLL getFieldsBLL = new GetFieldsBLL();
DataView dv = getFieldsBLL.GetWholeView(ViewName);
Task task = new Task(() => ucDataExtracViewControl.PopulateGrid(dv));
task.Start();
}

public void PopulateGrid(DataView dv)
{
dgView.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(delegate{

dgView.Columns.Clear();
dgView.AutoGenerateColumns = false;
foreach (DataColumn column in dv.Table.Columns)
{
var gridColumn = new DataGridTextColumn()
{
Header = column.ColumnName,
Binding = new Binding("[" + column.ColumnName + "]")
};

dgView.Columns.Add(gridColumn);
}
dgView.DataContext = dv;

DataView = dv;
}));
}

提前致谢!

编辑:我重新创建列的原因是因为某些列名称中有一个点。例如“作业编号”。使用绑定(bind)时不产生任何数据。在这里阅读更多:What is it about DataTable Column Names with dots that makes them unsuitable for WPF's DataGrid control?它不是对数据库进行更改的选项。 –

最佳答案

我经常使用 WPF DataGrid,但呈现是个问题。最后,渲染时间取决于您将要显示的列和行的数量。当 DataGrid 呈现时,它必须绘制每个内容,这意味着加载和测量内容的大小。

我发现通过设置固定的列宽和行高可以显着提高速度。当与下面的 DelayedDataGridTextColumn 结合使用时,UI 线程几乎没有阻塞,因为每个单元格都是单独呈现的,因此允许其他事情在具有更高优先级的 UI 线程上发生。

public class DelayedDataGridTextColumn : DataGridTextColumn
{
protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
{
var textBlock = new TextBlock();
textBlock.SetValue(FrameworkElement.StyleProperty, ElementStyle);

Dispatcher.BeginInvoke(
DispatcherPriority.Loaded,
new Action<TextBlock>(x => x.SetBinding(TextBlock.TextProperty, Binding)),
textBlock);
return textBlock;
}
}

请注意,您可以调整 DispatcherPriority 以适应您想要的渲染速度。优先级越低,您获得的窗帘效果就越多。优先级越高,渲染时处理的其他项目就越少。

关于c# - WPF DataGrid 和多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11134312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com