Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

c# - How to remove a image children from a stackpanel

I have a Stackpanel with 7 images inside, each image represents a domino tile. When the user drags and drops a image into a canvas called Board, the image should disappear from the Stackpanel. For more context this is the code in xaml:

<Canvas x:Name="Board" Grid.Row="2" AllowDrop="True" Background="Transparent" Drop="DropImage"/>

<StackPanel x:Name="TilesPlayer1" Grid.Row="3" AllowDrop="True" Orientation="Horizontal" HorizontalAlignment="Center" Margin="10" />

The domino tiles are added to the Stackpanel in a method inside the cs and therefore do not have a name or identifier. This is the code that I have to drag them and it works but I have several problems. Here is the C# code:

private void DragImage(object sender, MouseButtonEventArgs e)
    {
        Image image = e.Source as Image;
        DataObject data = new DataObject(typeof(ImageSource), image.Source);
        DragDrop.DoDragDrop(image, data, DragDropEffects.Move);
    }

    private void DropImage(object sender, DragEventArgs e)
    {
        ImageSource image = e.Data.GetData(typeof(ImageSource)) as ImageSource;

        Image imageControl = new Image() { Width = image.Width, Height = image.Height, Source = image };
        Canvas.SetLeft(imageControl, e.GetPosition(Board).X);
        Canvas.SetTop(imageControl, e.GetPosition(Board).Y);
        Board.Children.Add(imageControl);
    }

The code works but not how I would like.

  • It allows me to drag the image I want to the canvas but the size is not respected and if I try to handle it in another way the image does not appear inside the canvas.
  • The main problem that I cannot correct is that the image is copied, but I cannot remove it from the Stackpanel. I investigated and found that because it is an image I cannot delete it since to remove it from the Stackpanel it must be a UIElement and I cannot find how to solve it.

I hope you can help me.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...