Canvas.children: System.ArgumentException: 'Specified index is already in use. Disconnect the Visual child at the specified index first.'

Viewed 149

At the moment I am trying to assing a new value to one of canvas' children in wpf and it throws the exeption above I have the following code which I think is relavent:

var val = comps[0].GetComponent();
c.Children[comps[0].Index] = val;

Intrestingly the problem self-resolves when I do this:

var val = comps[0].GetComponent();
c.Children.RemoveAt(comps[0].Index);
c.Children.Insert(comps[0].Index, val);

but I want to understand whats happening and if there is a more efficient way of preventing the exeption

1 Answers

What's happening is that the System.Windows.Media.VisualCollection class explicitly checks whether the index in the collection that you are trying to assign a new value to is already in use and if it is, it throws an ArgumentException. Look at line 379 in the source code:

if (child != null)
{
    throw new System.ArgumentException(SR.Get(SRID.VisualCollection_EntryInUse));
}

So, as you already do, you should explicitly check if there is an element at the index and remove it before you try to insert a new item:

int index = 0;
if (canvas.Children.Count > index)
{
    canvas.Children.Remove(canvas.Children[index]);
}
canvas.Children.Insert(index, val);
Related