Search code examples
c#uwpdrag-and-dropgrid

c# uwp drag and drop - cant make a swap


so i i hade 10x10 grid with pics and i want to swap by drag and drop and i actually cant get the imgages the targeted and the selected in order to make the spaw i made all from view model code in the evens the sender is a grid and the e is DragEventArgs

      public MainViewModel()
    {
        GameGrid = new Grid { AllowDrop = true };
        GameGrid.DragOver += GameGrid_DragOver;
        GameGrid.Drop += GameGrid_Drop;

        for (int row = 0; row < 10; row++)
        {
            GameGrid.RowDefinitions.Add(new RowDefinition());
            for (int col = 0; col < 10; col++)
            {
                if (row == 0)
                    GameGrid.ColumnDefinitions.Add(new ColumnDefinition());

                var image = new Image { Source = logic.GetImage(), CanDrag = true, AllowDrop = true };
                Grid.SetRow(image, row);
                Grid.SetColumn(image, col);
                GameGrid.Children.Add(image);
            }
        }

    }

    private void GameGrid_DragOver(object sender, Windows.UI.Xaml.DragEventArgs e)
    {

        e.AcceptedOperation = DataPackageOperation.Move;
    }
    private async void GameGrid_Drop(object sender, Windows.UI.Xaml.DragEventArgs e)
    {
        if (logic.IsValidSwap(selected, selected))
        {
        }
    }

// but i cant get the imeges to send the func is validswap


Solution

  • Instead of assigning in the event to the grid:

    GameGrid.DragOver += GameGrid_DragOver; 
    GameGrid.Drop += GameGrid_Drop;
    

    It should be assigned to each image inside the for loop:

    image.Drop += GameGrid_Drop; 
    image.DragOver += GameGrid_DragOver;
    

    And than the sender will be the image—you can know the col and row and make switches.