c# - WPF - 用户控件非常慢

标签 c# wpf user-interface user-controls propertygrid

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

我为每个属性创建了一个自定义用户控件。现在令我震惊的是,表现非常糟糕。如果我有大约 100 个属性,则需要 500 毫秒才能在 StackPanel/Listbox 中显示它们。

我做了一个实验,将 200 个默认用户控件添加到 StackPanel。大约用了 50 毫秒。我认为仍然是一个非常高的数字。

我不应该为此目的使用用户控件吗?这样做似乎非常面向对象,我真的看不到其他解决方案。

但是我可以看到 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 毫秒。如果我更改为我自己的自定义用户控件,它会高得多。我可能会补充说,滚动不是问题。

编辑2:

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

编辑 3: 除了 InitializeComponent 方法之外,我的用户控件的构造函数中没有发生任何事情。这是我正在添加的用户控件的示例。

<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,0,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,0,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
}

这将导致调度程序在您添加控件时停止处理消息,并在最后一次完成整个布局和渲染。

关于c# - WPF - 用户控件非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4824792/

相关文章:

c# - 数字文本框

c# - 在 linq c# 中使用 where 条件对列表进行排序

c# - 选择行时修改 ListView 的行行为

c# - 单元测试元数据类型

wpf - 在WPF中显示多个对话框是否安全?

c# - 嵌套的 RibbonApplicationMenuItem 出错

javascript - 《金融时报》如何在粘贴文本时添加免责声明?

jQuery ui : Draggable, 如何确定图像在 x 轴上移动了多少?

android UI Material 风格

c# - Ghostscript.NET 如何处理 StdIn 上的输入