Michael
Michael

Reputation: 3150

How do I speed up a rendering of a WPF control with a lot of data?

I have a user control that often has 2000 or so component controls (TextBoxes, TextBlocks, ComboBoxes, etc.), and my application doesn't run as fast as I'd like.

While 2000 controls may seem like a lot at first, it is really only representative of a WPF data grid that has 10 columns and 200 rows - a common scenario in many applications.

Here's an extremely simple sample that I believe mimics such a data grid, and I'm seeing a 200ms or so render time:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        Loaded += MainWindow_Loaded;
    }

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        Stopwatch stopwatch = Stopwatch.StartNew();

        ScrollViewer scrollViewer = new ScrollViewer();
        StackPanel stackPanel = new StackPanel();

        for (int rowIndex = 0; rowIndex < 200; rowIndex++)
            for (int columnIndex = 0; columnIndex < 10; columnIndex++)
                stackPanel.Children.Add(new TextBlock { Text = Guid.NewGuid().ToString() });

        scrollViewer.Content = stackPanel;
        this.Content = scrollViewer;

        UpdateLayout(); // Force a UI layout so we can get an accurate stopwatch reading
        MessageBox.Show(stopwatch.Elapsed.ToString(), "UI Layout Time");
    }

This is as simple as I can think to make this example, but 200 ms is still enough for a user to notice and potentially think the software is slow.

If this were a real control with a data grid, the controls would be very likely be more complex than TextBlocks and potentially have further time sucks like IValueConverters and Styles / DataTemplates.

Is there anything I can do to speed up the load time of controls that have a lot of data?

Upvotes: 0

Views: 2136

Answers (1)

Andrey
Andrey

Reputation: 60065

Check the concept: UI Virtualization. It should help if you don't have too much controls on viewable area.

Upvotes: 3

Related Questions