WPF - 用户控件非常缓慢

5
我正在设计一个类似于PropertyGrid的东西,我想显示对象的属性。由于某些特殊原因,我不打算使用PropertyGrid而是创建自己的控件。
为每个属性创建了自定义用户控件。现在我的问题是性能非常差。如果我有100个属性,将它们显示在StackPanel/Listbox中需要500毫秒。
我进行了一个实验,在StackPanel中添加200个默认的UserControls。大约需要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:

好的。这与stackpanel无关。我已经发现创建用户控件是一个非常昂贵的操作。如果您有任何其他想法,我很乐意听取 :)

编辑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>


1
嗨,伙计。我有类似的问题。渲染很快,但创建非常慢。仍然没有找到解决方案。 - GorillaApe
1个回答

6

我怀疑您在添加数百个子元素时会触发很多布局更新。

如果这是瓶颈,您可以考虑执行以下操作:

using(var suspend = Dispatcher.DisableProcessing())
{
       // Add all children here
}

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

1
看起来很有前途! 等我测试完并告诉你结果后,会在接下来的24小时内回复。 - Mads Andersen
@bobjink: 有趣 - 你的用户控件在其构造函数中执行工作吗?能否发布显示您在构建/添加期间所做内容的代码? - Reed Copsey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接