I have a list with images and their left / top locations, which I add to the canvas. However, I want to be able to add the same images (same source) to the Canvas, without any problems.
When I just use the following code:
Image img = ImagesList[i].Image;
img.Name = "img" + i;
Canvas.SetLeft(img, ImagesList[i].Left);
Canvas.SetTop(img, ImagesList[i].Top);
MyCanvas.Children.Add(img);
OnPropertyChanged("MyCanvas");
when the same Image (-source) is already present on the Canvas (with a different left / top location and name), I get the following exception:
ArgumentException: Specified Visual is already a child of another Visual or the root of a CompositionTarget.
So, I know that I am not allowed to add the same UIElement (in my case Image) to the same Canvas.
I changed my code to:
if (MyCanvas.Children.Contains(img)) {
Image cloneImg = new Image();
cloneImg.Source = img.Source;
cloneImg.Name = img.Name;
Canvas.SetLeft(cloneImg, Left);
Canvas.SetTop(cloneImg, Top);
MyCanvas.Children.Add(cloneImg);
}
else
MyCanvas.Children.Add(img);
OnPropertyChanged("MyCanvas");
, . , ( ) reset 0,0 ( , ), Console.Write-test, , .
, , Left, Top (, , ) , ( "Clone" )?
.
EDIT: xaml :
<Canvas Name="MyCanvas" Background="LimeGreen"/>
To:
<ItemsControl ItemsSource="{Binding MyField.ImagesList}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Name="FieldCanvas" Background="LimeGreen" IsItemsHost="True"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left" Value="{Binding Left}"/>
<Setter Property="Canvas.Top" Value="{Binding Top}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Image Source="{Binding ImageSource}" AllowDrop="True" PreviewMouseLeftButtonDown="Image_PreviewMouseLeftButtonDown" PreviewMouseMove="Image_PreviewMouseMove" PreviewMouseLeftButtonUp="Image_PreviewMouseLeftButtonUp"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
"ImagesList" BitmapImage Images Image Image.
, . Canvas ViewModel, , , , ItemsControl.
MouseEvent, img.Parent, Canvas ( ) canvas.Children, , ZIndex ( isn ).
EDIT2/:
Edit , - , , ImageSource, , , .