wpf - 如何提高 WPF 网格控件 (.NET 4.0/4.5) 的性能?

标签 wpf wpf-controls wpfdatagrid wpf-4.0 wpf-4.5

定义:将二维字符串数组(约10列,1,600行,固定长度7个字符)作为WPF .NET 4.0网格控件的数据源,以下代码片段已用于使用显示数组值的标签填充网格。 注意:网格已添加到 XAML 并传递给函数 PopulateGrid(参见 list 1)。可视化输出本质上是只读模式下的表格数据表示(无需双向绑定(bind))。

问题:性能是一个关键问题。在功能强大的 Intel-i3/8GB-DDR3 PC 上运行此操作花费了令人难以置信的 3...5 秒;因此,基于与类似控件/任务的比较,恕我直言,此 WPF 网格性能至少比预期慢一个数量级。常规 WinForm 数据感知控件,甚至 Excel 工作表。

问题 1:在上述场景中是否有提高 WPF Grid 性能的方法?请将您的答案/可能的改进指向下面 list 1 和 list 2 中提供的代码片段。

问题 1a:提议的解决方案可以将数据绑定(bind)到其他数据感知控件,例如 DataGridDataTable .我添加了 string[,]DataTable dt list 2 中的转换器,以便附加控件的 DataContext (或 ItemsSource ,随便什么)属性可以绑定(bind)到 dt.DefaultView .因此,以最简单的形式,您能否提供一个关于 WPF 的 数据绑定(bind)的紧凑(最好是几行代码,就像在旧式数据感知控件中所做的那样)和高效(性能方面)的解决方案DataGridDataTable对象 ?

非常感谢。

list 1。填充 WPF 的过程 Grid GridOut来自 2D string[,] Values

#region Populate grid with 2D-array values
/// <summary>
/// Populate grid with 2D-array values
/// </summary>
/// <param name="Values">string[,]</param>
/// <param name="GridOut">Grid</param>
private void PopulateGrid(string[,] Values, Grid GridOut)
{
    try
    {
        #region clear grid, then add ColumnDefinitions/RowsDefinitions

        GridOut.Children.Clear();
        GridOut.ColumnDefinitions.Clear();
        GridOut.RowDefinitions.Clear();

        // get column num
        int _columns = Values.GetUpperBound(1) + 1;

        // add ColumnDefinitions
        for (int i = 0; i < _columns; i++)
        {
            GridOut.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
        }

        // get rows num
        int _rows = Values.GetUpperBound(0) + 1;

        // add RowDefinitions
        for (int i = 0; i < _rows; i++)
        {
            GridOut.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
        }
        #endregion

        #region populate grid w/labels
        // populate grid w/labels
        for (int i = 0; i < _rows; i++)
        {
            for (int j = 0; j < _columns; j++)
            {
                // new Label control
                Label _lblValue = new Label();

                // assign value to Label
                _lblValue.Content = Values[i, j].ToString();

                // add Label to GRid
                GridOut.Children.Add(_lblValue);
                Grid.SetRow(_lblValue, i);
                Grid.SetColumn(_lblValue, j);
            }
        }
        #endregion
    }
    catch
    {
        GridOut.Children.Clear();
        GridOut.ColumnDefinitions.Clear();
        GridOut.RowDefinitions.Clear();
    }
}
#endregion

list 2string[,]DataTable转换

#region internal: Convert string[,] to DataTable
/// <summary>
/// Convert string[,] to DataTable
/// </summary>
/// <param name="arrString">string[,]</param>
/// <returns>DataTable</returns>
internal static DataTable Array2DataTable(string[,] arrString)
{
    DataTable _dt = new DataTable();
    try
    {
        // get column num
        int _columns = arrString.GetUpperBound(1) + 1;

        // get rows num
        int _rows = arrString.GetUpperBound(0) + 1;

        // add columns to DataTable
        for (int i = 0; i < _columns; i++)
        {
            _dt.Columns.Add(i.ToString(), typeof(string));
        }

        // add rows to DataTable
        for (int i = 0; i < _rows; i++)
        {
            DataRow _dr = _dt.NewRow();
            for (int j = 0; j < _columns; j++)
            {
                _dr[j] = arrString[i,j];
            }
            _dt.Rows.Add(_dr);
        }
        return _dt;
    }
    catch { throw; }
}
#endregion

注释 2。建议替换为Label控制带 TextBlockLabel 的情况下使用其 Text 属性而不是 Content .它会稍微加快执行速度,而且代码片段将向前兼容 VS 2012 for Win 8,其中不包括 Label。 .

注意 3:到目前为止我已经尝试绑定(bind) DataGridDataTable (参见 list 3 中的 XAML),但性能很差( grdOut 是嵌套的 Grid ,用作表格数据的容器;_ dataGridDataGrid 的数据感知对象类型) .

list 3DataGrid绑定(bind)到 DataTable : 性能很差,所以我删除了 ScrollViewer而不是它运行正常。

<ScrollViewer ScrollViewer.CanContentScroll="True" VerticalScrollBarVisibility="Auto" >
    <Grid Name="grdOut">
            <DataGrid AutoGenerateColumns="True" Name="_dataGrid" ItemsSource="{Binding Path=.}" />
    </Grid>
</ScrollViewer>

最佳答案

好的。删除所有代码并重新开始。

这是我对 Labels 的“动态网格”的看法,其中 X 行数和 Y 列数基于二维字符串数组:

<Window x:Class="MiscSamples.LabelsGrid"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="LabelsGrid" Height="300" Width="300">
    <DockPanel>

        <Button DockPanel.Dock="Top" Content="Fill" Click="Fill"/>

        <ItemsControl ItemsSource="{Binding Items}"
                      ScrollViewer.HorizontalScrollBarVisibility="Auto"
                      ScrollViewer.VerticalScrollBarVisibility="Auto"
                      ScrollViewer.CanContentScroll="true"
                      ScrollViewer.PanningMode="Both">
            <ItemsControl.Template>
                <ControlTemplate>
                    <ScrollViewer>
                        <ItemsPresenter/>
                    </ScrollViewer>
                </ControlTemplate>
            </ItemsControl.Template>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <ItemsControl ItemsSource="{Binding Items}">
                        <ItemsControl.ItemTemplate>
                            <DataTemplate>
                                <Label Content="{Binding}"/>
                            </DataTemplate>
                        </ItemsControl.ItemTemplate>
                        <ItemsControl.ItemsPanel>
                            <ItemsPanelTemplate>
                                <UniformGrid Rows="1"/>
                            </ItemsPanelTemplate>
                        </ItemsControl.ItemsPanel>
                    </ItemsControl>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <VirtualizingStackPanel VirtualizationMode="Recycling" IsVirtualizing="True"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
    </DockPanel>
</Window>

代码隐藏:

public partial class LabelsGrid : Window
{
    private LabelsGridViewModel ViewModel { get; set; }

    public LabelsGrid()
    {
        InitializeComponent();
        DataContext = ViewModel = new LabelsGridViewModel();
    }

    private void Fill(object sender, RoutedEventArgs e)
    {
        var array = new string[1600,20];

        for (int i = 0; i < 1600; i++)
        {
            for (int j = 0; j < 20; j++)
            {
                array[i, j] = "Item" + i + "-" + j;
            }
        }

        ViewModel.PopulateGrid(array);
    }
}

View 模型:

public class LabelsGridViewModel: PropertyChangedBase
{
    public ObservableCollection<LabelGridItem> Items { get; set; } 

    public LabelsGridViewModel()
    {
        Items = new ObservableCollection<LabelGridItem>();
    }

    public void PopulateGrid(string[,] values)
    {
        Items.Clear();

        var cols = values.GetUpperBound(1) + 1;
        int rows = values.GetUpperBound(0) + 1;

        for (int i = 0; i < rows; i++)
        {
            var item = new LabelGridItem();

            for (int j = 0; j < cols; j++)
            {
                item.Items.Add(values[i, j]);
            }

            Items.Add(item);
        }
    }
}

数据项:

public class LabelGridItem: PropertyChangedBase
{
    public ObservableCollection<string> Items { get; set; }

    public LabelGridItem()
    {
        Items = new ObservableCollection<string>();
    }
}

PropertyChangedBase 类(MVVM 助手)

public class PropertyChangedBase:INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        Application.Current.Dispatcher.BeginInvoke((Action) (() =>
                                                                 {
                                                                     PropertyChangedEventHandler handler = PropertyChanged;
                                                                     if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
                                                                 }));
    }
}

结果:

enter image description here

  • 性能非常棒。请注意,我使用的是 20 列而不是您建议的 10 列。当您单击按钮时,网格的填充是立即的。由于内置 UI 虚拟化,我确信性能比蹩脚的恐龙 winforms 好得多。

  • UI 是在 XAML 中定义的,而不是在过程代码中创建 UI 元素,这是一种不好的做法。

  • UI 和数据保持分离,从而提高了可维护性、可扩展性和清洁度。

  • 将我的代码复制并粘贴到 File -> New -> WPF Application 中,然后亲自查看结果。

  • 此外,请记住,如果您只打算显示文本,最好使用 TextBlock 而不是 Label,这是一个轻量级的文本元素。

  • WPF 非常棒,即使在边缘情况下它可能会导致性能下降,它仍然比目前存在的任何东西都要好 12837091723。

编辑:

我继续往行数 (160000) 中添加 0 个零。性能还是可以接受的。填充网格用时不到 1 秒。

请注意,在我的示例中,“列”并未被虚拟化。如果它们数量很多,这可能会导致性能问题,但这不是您所描述的。

编辑2:

根据您的评论和说明,我制作了一个新示例,这次基于 System.Data.DataTable。没有 ObservableCollections,没有异步的东西(无论如何在我之前的例子中没有任何异步)。只有 10 列。水平滚动条出现是因为窗口太小 (Width="300"),不足以显示数据。 WPF 独立于分辨率,与恐龙框架不同,它在需要时显示滚动条,但也会将内容拉伸(stretch)到可用空间(您可以通过调整窗口大小等方式看到这一点)。

我还将数组初始化代码放在 Window 的构造函数中(以处理缺少 INotifyPropertyChanged),因此加载和显示它会花费更多时间,我注意到这个示例使用 System.Data.DataTable 比前一个稍微慢一些。

但是,我必须警告你Binding to Non-INotifyPropertyChanged objects may cause a Memory Leak .

不过,您将无法使用简单的 Grid 控件,因为它不执行 UI 虚拟化。如果您想要虚拟化网格,则必须自己实现。

您也将无法使用 winforms 方法来解决这个问题。它在 WPF 中根本无关紧要且毫无用处。

    <ItemsControl ItemsSource="{Binding Rows}"
                  ScrollViewer.HorizontalScrollBarVisibility="Auto"
                  ScrollViewer.VerticalScrollBarVisibility="Auto"
                  ScrollViewer.CanContentScroll="true"
                  ScrollViewer.PanningMode="Both">
        <ItemsControl.Template>
            <ControlTemplate>
                <ScrollViewer>
                    <ItemsPresenter/>
                </ScrollViewer>
            </ControlTemplate>
        </ItemsControl.Template>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <ItemsControl ItemsSource="{Binding ItemArray}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding}"/>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <UniformGrid Rows="1"/>
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                </ItemsControl>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <VirtualizingStackPanel VirtualizationMode="Recycling" IsVirtualizing="True"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>

代码隐藏:

public partial class LabelsGrid : Window
{
    public LabelsGrid()
    {
        var array = new string[160000, 10];

        for (int i = 0; i < 160000; i++)
        {
            for (int j = 0; j < 10; j++)
            {
                array[i, j] = "Item" + i + "-" + j;
            }
        }

        DataContext = Array2DataTable(array);
        InitializeComponent();
    }

    internal static DataTable Array2DataTable(string[,] arrString)
    {
        //... Your same exact code here
    }
}

底线是要在 WPF 中做某事,您必须以 WPF 方式来做。它不仅仅是一个 UI 框架,它本身更像是一个应用程序框架。

编辑3:

<DataGrid AutoGenerateColumns="True" ItemsSource="{Binding}"/>

 DataContext = Array2DataTable(array).DefaultView;

非常适合我。 160000 行的加载时间并不明显。您使用的是哪个 .Net 框架版本?

关于wpf - 如何提高 WPF 网格控件 (.NET 4.0/4.5) 的性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16659265/

相关文章:

c++ - XPS开源实现?

c# - 如何在 C# 中获取网格的行数和列数?

.net - WebBrowser(WPF 和 WinForms 控件)和 JSON 对象 - JSON 未定义

wpf - 无法通过类型(!)(wpf)找到模板化控件的父级

c# - Wpf DataGrid SelectedItem 在单元格编辑后失去绑定(bind)

wpf - 带有 DataGrid WPF 的复选框

wpf - 在一行中绑定(bind) ValidationRules?

wpf - 如何从 ItemsControl 中的 ItemTemplate 获取控件?

c# - 在 WPF DataGrid 中保留用户定义的排序顺序

c# - MVVM 通用 app.config