WPF User Control is causing Out of Memory Exception

Posted by Chairman Meow on Stack Overflow See other posts from Stack Overflow or by Chairman Meow
Published on 2010-03-08T23:49:53Z Indexed on 2010/03/08 23:51 UTC
Read the original article Hit count: 413

Looking for a free spell checking solution, I thought I was so smart in doing this but I guess not.

I have created a windows form based application and I want the form to add a user specified amount of user controls (with textboxes) on to a panel. The user can then click some button and the controls on this panel are cleared and new ones are added. The user does something and the process is repeated. Now, I wanted these textboxes to support spell checking and looked all over for a free solution.

WPF textboxes support spell checking where the ones in regular win forms do not. I thought I would be able to use these WPF textboxes by adding them to an ElementHost object which is, in turn, within a panel. This panel would be a user control.

So, in my application, I would be able to add instances of these user controls onto the form and make use of .NET's spell checking goodness. This actually worked but after using the application for a while, found that the application would eventually freeze on me due to out of memory errors. I have pinpointed the memory errors to these WPF controls since this problem does not happen with normal textboxes.

When the window is opened and the number of controls is specified, this is pretty much how the controls are added:

Dim xOffset As Integer = 0
For i As Integer = 0 To theNumber
    Dim myUserControl As New SpecialUserControl()
    myPanel.Controls.Add(myUserControl)
    myUserControl.Location = New Point(7, 7)
    myUserControl.Location = New Point(xOffset, 7)
    xOffset = xOffset + 207
Next

Note that:

  • myPanel is a panel on a form
  • SpecialUserControl is the user control with WPF textbox (within an ElementHost object)

When the user pressed a button, the panel is cleared:

myUserControl.Controls.Clear()

The user can then repeat the process.

There are a lot of results on the internet when I tried to find a solution and I'm thinking that the problem I am having is due to the fact that the WPF control is not going away even after clearing the panel. Following this conclusion, I have tried different solutions regarding disposing these controls or setting them to nothing but the memory problem keeps occurring. If someone could give me some advice or ideas here, I'd really appreciate it.

© Stack Overflow or respective owner

Related posts about wpf-controls

Related posts about winforms