views:

33

answers:

2

Hi,

I have a list box that I'm trying to populate with a list of viewboxes. The listbox takes in the list without a problem. However, when my function reaches its end, I receive the error:

"Must disconnect specified child from current parent Visual before attaching to new parent Visual."

The viewboxes are created from the same initial viewbox and then edited, which I believe may be my problem.

for(...)
{
        Viewbox newviewbox = (Viewbox)myViewbox; //myViewbox created in XAML
        // edits newviewbox here
        viewboxlist.Add(newviewbox); //viewboxlist created upon initialization
        newviewbox = null;
    }
myListBox.ItemsSource = viewboxlist;

Any advice is greatly appreciated.

Thanks.

A: 

You are not creating new viewboxes, you are just referencing the same viewbox and adding it to the list several times. Thus the error that the viewbox already have a parent and should be disconnected before assigning it to a new parent.

You should create new instances of ViewBox like this:

var newViewBox = new ViewBox();
Peter Lillevold
Thank you both for the quick response. Peter, if I create a new viewbox each iteration of the for loop, can I still set the new viewboxes equal to the one defined in XAML? I'm currently doing so, and still receive the same error. var newviewbox = new ViewBox();newviewbox = myViewboxIf not, is there a workaround to use that initial viewbox as a template? (Binding won't work as I need to use parameters from the code behind... I think)Thanks much.
andrew
Sure you get the same error, you are not creating a new copy of the element, you are only copying the *reference* to the same element. You should throw out the element in xaml and create/initialize new instances on each iteration (yes, all properties you have previously set in xaml can also be set with code). Or more preferable, you could go for data binding and use an element in xaml as a template. You should read up on data binding and data templates to get a grip on that, it is a very powerful feature of wpf.
Peter Lillevold
A: 

A Visual can only have one parent. In your code, you're taking an existing Visual and try to add it to another parent (the ListBox), so it can't work. You have to either remove it from the original parent, or create a new one

Thomas Levesque