Search code examples
c#wpfdrag-and-drop

How do I capture the drop event in the background of my control?


I have a bunch of controls of the same type on one screen and am trying to implement drag and drop to change the order of the items.

The drag and drop logic I wrote works fine, my problem is that my control has a bunch of whitespace. Everything is enclosed in a border, but about 50% of that area is not filled with more sub-controls.

In the following image, the pen is my cursor, and it shows me I can drop on the image.

image showing a pen as cursor when hovering an image while dragging an item

The cursor turns into a pen for every control inside the border (the image, the text, the green and red buttons on the bottom, and the orange dot in the top right corner)

In this image, the red cross is my cursor, and it shows me I cannot drop it on the background inside the border.

image showing a red cross as cursor when hovering the background of my control

The cursor turns into a red cross in any place where the background can be seen.

How do I make sure the whole area inside the border is considered a drop-area?


Solution

  • The issue was indeed that there was no background inside my custom control. I fixed it by filling the border with a transparent background rectangle:

    <local:MyCustomControl
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:MyNamespace.Client"
        x:Class="MyNamespace.Client.Controls.MyCustomControl"
        Margin="2" Padding="0" Height="Auto" Foreground="Black" AllowDrop="True">
        <Grid>
            <Rectangle Grid.Column="0" Grid.Row="0" Width="{Binding Path=ActualWidth, ElementName=border}" Height="{Binding Path=ActualHeight, ElementName=border}" Fill="Transparent"></Rectangle>
            <Border Name="border" BorderThickness="0.5" BorderBrush="LightGray" Grid.Column="0" Grid.Row="0" >
                <!-- content goes here -->
            </Border>
        </Grid>
    </local:MyCustomControl>