Problems when adding tabitems dynamically

3 posts, 1 answers
  1. hwsoderlund
    hwsoderlund avatar
    419 posts
    Member since:
    Aug 2006

    Posted 13 Oct 2008 Link to this post

    Hi, I'm receiving the following error message when I'm trying to add tab items dynamically to a tabcontrol inside a radwindow:  "Element is already the child of another element."
    I've uploaded a sample project so you can see what's going on. Basically I'm trying to create a "master" control with the tabcontrol and one initial tabitem. Then I add the other tab items through a dependency property in the child user controls. The problem occurs when you close the first window and then try to open it again. I'm not sure whether this is a problem in your component or if there's something wrong with my own code. I would appreciate it if you could just take a look and see if this problem is something you've come across before.

    http://cid-cc43a90a79374ebd.skydrive.live.com/self.aspx/Public/SilverlightApplication10.zip
  2. Answer
    Miroslav
    Admin
    Miroslav avatar
    922 posts

    Posted 14 Oct 2008 Link to this post

    Hello Henrik,

    Thank you for your example, this makes debugging a lot easier!

    the problem in this case is the way DependencyProperties work - setting a collection as a default value of a dependency property yields unexpected results.

    Since a default value (a an object reference will always exist as a value) to the dependency property, this object will be shared, kind of static. So each next instance of the master control will add 2 new TabItems. That can be clearly seen when you debug your project and check the count of the items. With the first instance they are 2, the second 4 and they will get more and more if this could continue.

    In essence, the TabControl was trying to add items that were already items of another control.

    I would not imagine this is production code, but other good practices include exposing collection properties as interfaces (IList<Somethning>) and using ObservableCollection<Something> (which can be assigned to an IList) when the items are going to be bound as an ItemsSource.

    This blog gives more information on the Collection Dependency properties:

    http://blogs.telerik.com/ManolDonev/Posts/08-07-25/WPF_The_Static_Nature_of_Dependency_Properties.aspx

    To resolve the issue, simply set a local (and therefore unique) value to the property:

    TabItems

     

    = new List<RadTabItem>();

     

    Kind regards,
    Miroslav
    the Telerik team

    Check out Telerik Trainer, the state of the art learning tool for Telerik products.
  3. DevCraft banner
  4. hwsoderlund
    hwsoderlund avatar
    419 posts
    Member since:
    Aug 2006

    Posted 14 Oct 2008 Link to this post

    That solves my problem. And thanks for the explanation, dependency properties are much clearer to me now.
Back to Top