How to fix the “Value does not fall within the expected range” exception when adding a child to a Control that has already been used

It is very simple. I went through several threads on various forums and did not find any code in any of them, and since this error is very common, I decided to write a workaround on my blog. It applies to WPF and Windows Store apps, and probably also to Silverlight and Windows Phone. To verify it, do the following:

  1. Create a global variable of type Popup named popup, and put a button on the page (Page) that will dynamically add another button to this popup using the Child property.
  2. Register a Click handler on the button in the Popup and put this code in its body:
    C#
    popup.IsOpen = false;
    VisualTreeHelper.DisconnectChildrenRecursive(popup);
  3. Comment out the second line of my code and try running it. The second time the popup is shown, a System.ArgumentException exception will be thrown. Uncomment the second line and it should work for you. In addition, I also give each element (both the popup and its child an incrementing ID with the class name, so if it does not work for you, do that as well – just to be safe).
Categories

Leave a Reply