c# – WPF – UserControls非常慢

我正在设计类似于PropertyGrid的东西,我想在其中显示对象的属性.出于特殊原因,我不打算使用PropertyGrid,而是创建自己的.

对于每个属性,我创建了一个自定义用户控件.令我恐惧的是,表现非常糟糕.如果我有100个属性,则需要500毫秒才能在StackPanel / ListBox显示它们.

我做了一个实验,在那里我向StackPanel添加了200个认UserControl.花了大约50毫秒.我认为仍然是一个非常高的数字.

我不应该将usercontrol用于此目的吗?这样做似乎非常面向对象,我无法真正看到另一种解决方案.

但是我可以看到PropertyGrid和TreeView表现良好,所以他们做了什么,我该怎么办?

编辑:

Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        using (var suspend = dispatcher.disableProcessing())
        {
            // Add all children here
            for (int i = 0; i < 200; i++)
            {
                this.propertiesstackPanel.Children.Add(new System.Windows.Controls.Button(){Content = "Testing"});
            }
        }
        stopwatch.Stop();

这仍然需要大约50毫秒.如果我更改为我自己的自定义用户控件,它会更高.我可能会补充说滚动不是问题.

EDIT2:

好.它与stackpanel无关.我发现这是因为创建UserControls是一项非常昂贵的操作.如果您对我该做什么有任何其他想法,我很乐意听到他们:)

EDIT3:
除了InitializeComponent方法之外,我的usercontrol的构造函数中没有任何内容.这是我正在添加用户控件的示例.

<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="PropertyBox.GroupUC"
x:Name="UserControl"
d:DesignWidth="640" d:DesignHeight="480" Background="#FF32B595" BorderThickness="0">

<Grid x:Name="LayoutRoot">
    <Grid.ColumnDeFinitions>
        <ColumnDeFinition Width="20px"/>
        <ColumnDeFinition Width="*"/>
    </Grid.ColumnDeFinitions>
    <Border x:Name="border" BorderThickness="0,1" Grid.Column="1">
        <TextBox Text="TextBox" textwrapping="Wrap" VerticalAlignment="Center" HorizontalAlignment="Right" BorderThickness="0" Padding="0" Visibility="Hidden"/>
    </Border>
    <Label x:Name="groupNameLabel" HorizontalAlignment="Left" Margin="5,0" VerticalAlignment="Center" Content="Label" Padding="0" Grid.Column="1"/>
    <Button x:Name="expandButton" HorizontalAlignment="Left" VerticalAlignment="Center" Width="12" Height="12" Content="" Click="ExpandButtonClick" Margin="4,0" Padding="0" Grid.ColumnSpan="2" d:IsHidden="True"/>
    <Image x:Name="expandButton2" Visibility="Hidden"  Width="12" Height="12" HorizontalAlignment="Center" VerticalAlignment="Center" Stretch="None"/>
</Grid>

解决方法

我怀疑你在添加数百个孩子的同时触发了许多布局更新.

如果这是瓶颈,您可能需要考虑:

using(var suspend = dispatcher.disableProcessing())
{
       // Add all children here
}

这将导致调度程序在您添加控件时停止处理消息,并执行整个布局并在最后一次渲染中进行渲染.

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...