I have a user control that has a grid (one that you get automatically when you create a user control) and a canvas inside that.
<Grid x:Name="LayoutRoot" Background="White">
<Canvas x:Name="SurfaceCanvas">
</Canvas>
</Grid>
In the CS file, I defined the "Items" collection.
public ObservableCollection<TestItem> Items {
get { return (ObservableCollection<TestItem>)GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}
public static readonly DependencyProperty ItemsProperty =
DependencyProperty.Register("Items", typeof(ObservableCollection<TestItem>),
typeof(TestControl),
new PropertyMetadata(new ObservableCollection<TestItem>()));
TestItem class declaration:
public class TestItem : ContentControl { ... }
Elements are added to it through XAML.
<my:TestControl x:Name="ControlOne" Height="100" Width="100">
<my:TestControl.Items>
<my:TestItem x:Name="ItemOne">One</my:TestItem>
</my:TestControl.Items>
</my:TestControl>
<my:TestControl x:Name="ControlTwo" Height="100" Width="100">
<my:TestControl.Items>
<my:TestItem x:Name="ItemTwo">Two</my:TestItem>
</my:TestControl.Items>
</my:TestControl>
When items are added to the collection, I add them to the canvas.
void Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) {
switch(e.Action) {
case NotifyCollectionChangedAction.Add:
foreach(Control item in e.NewItems) {
SurfaceCanvas.Children.Add(item);
}
break;
}
}
Now the problem.
If there is one instance of this control, all is well. But when I define the second instance, I get InvalidOperationException: "The element is already a descendant of another element" in the element added to ControlTwo.
, , , ItemOne ControlOne, ItemTwo ControlOne, ControlTwo. , , .
, - , , , "SurfaceCanvas", . , .
?