I am creating something similar to a PropertyGrid where I want to show the properties of objects. For special reasons, I will not use the PropertyGrid, but create my own.
For each property, I created a custom user control. Now, to my horror, the performance is very poor. If I have something like 100 properties, it takes 500 milliseconds to display them in the StackPanel / Listbox.
I did an experiment in which I add 200 standard UserControls to the StackPanel. It took about 50 milliseconds. Still a very large number, I think.
Should usercontrol be used for this purpose? It seems very object oriented to do it this way, and I cannot see another solution.
However, I see that the PropertyGrid and TreeView work well, so what did they do and what should I do?
Edit:
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
using (var suspend = Dispatcher.DisableProcessing())
{
for (int i = 0; i < 200; i++)
{
this.propertiesStackPanel.Children.Add(new System.Windows.Controls.Button(){Content = "Testing"});
}
}
stopwatch.Stop();
It takes about 50 milliseconds anyway. If I switch to my own user control, it will be much higher. I could add that scrolling is not a problem.
Edit2:
OK This has nothing to do with the stackpanel. I found out that this is because creating UserControls is a very expensive operation. If you have a different idea of what to do, I would love to hear them :)
Edit3:
Nothing happens in the constructor of my usercontrol except the InitializeComponent method. Below is an example of user control that I am adding.
<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>