c# - WPF DataGrid 和多线程

标签 c# wpf multithreading

我有一个用 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/

相关文章:

c# - 这个 do...while 循环 C# 有什么问题?

c# - 将包含条件的小字符串值转换为代码(或动态评估条件的最佳方式)?

c# - 如何从 ViewModel 读取 TextBox 焦点 - MVVM Light

wpf - wpf中如何改变标题栏的高度

c# - async 和 await 是否会提高 ASP.Net 应用程序的性能

c# - 布局和 View 上的信号器连接

c# - 是否可以注入(inject)绑定(bind)为子选项的特定配置类而不是 IConfiguration<MyType>?

c# - 将 WebClient 转换为 HttpClient

c# - 使用 WCF 服务行为属性设置为 ConcurrencyMode.Multiple 和 InstanceContextMode.PerCall 时是否可能出现并发问题?

multithreading - 为什么信号/槽不适用于多线程?