0

I'm trying to create a card game in WPF and I get the error: Specified Visual is already a child of another Visual or the root of a CompositionTarget. I have a window with a listview in it (named: handListview). The listview's itemssource is set to an

ObservableCollection<System.Windows.Controls.Image>

called _hand.

As I hover an image, it shows an enlargement of hovered image by having a mousemove event add the hovered image source to an Image control (called LargeCardPreview) .source, next to the play canvas..

When I double click an image, I'd have it removed from _hand and added as a child element to the play canvas called playCanvas. (I use playCanvas.Children.Add).

Here's where the problem comes in, when I double click the image, I remove the card from the _hand collection (which at first thought would disconnect the element from the HandListView since it was bound to the collection), and triggers a "OnCardPlayed" event. In this even I add the card to playCanvas.Children collection. But then I get the error.

I thought it might be because the LargeImagePreview was blocking it, so I set the source to Null. No change.

So I guess its because that even though I remove the card from the _hand observablecollection the image doesn't get disconnected immediately. So how do I force a disconnect?

Hope that my question is clear enough.

Daniel Olsen
  • 1,020
  • 2
  • 15
  • 27

1 Answers1

0

Instead of only trying to describe what your program does you should consider to also post the relevant code parts.

However there is one general problem with your approch. You should not use Image controls as ListView items when you also intend to display these image in other places of your application. Use ImageSource as item type (set ItemsSouce to an ObservableCollection<ImageSource>) and define an appropriate ItemTemplate for your ListView.

<ListView>
    <ListView.ItemTemplate>
        <DataTemplate>
            <Image Source="{Binding}"/>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Now when you add for example the ListView's SelectedItem to a Canvas, you would create a new Image control:

Image image = new Image { Source = list.SelectedItem as ImageSource };
Canvas.SetLeft(image, ...);
Canvas.SetTop(image, ...);
canvas.Children.Add(image);
Clemens
  • 123,504
  • 12
  • 155
  • 268