Bizhan
Bizhan

Reputation: 17085

How can I capture MouseEnter while dragging a Thumb?

I have a Thumb (containing a TextBlock) and a Border inside a Canvas. The Thumb receives Drag Events, and is dragging properly.

What I need is to capture MouseEnter Event on the Border while the Thumb is dragging .

The problem is MouseEnter is fired after DragCompleted Event (after the mouse button is released). How can I know when mouse enters the Border while the mouse button is down?

Xaml:

<Grid>
<Canvas Margin="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
    <Canvas Name="dragTarget">
        <Thumb
            DragStarted="Thumb_DragStarted" 
            DragDelta="Thumb_DragDelta"
            DragCompleted="Thumb_DragCompleted">
            <Thumb.Template>
                <ControlTemplate>
                    <TextBlock
                        Text="Some Text"
                        Foreground="White"
                        Background="DimGray"/>
                </ControlTemplate>
            </Thumb.Template>
        </Thumb>
    </Canvas>
    <Border Width="100" Height="100" Margin="50,50,0,0" 
        BorderBrush="AliceBlue" BorderThickness="1" Background="Silver"
        MouseEnter="Border_MouseEnter"/>
</Canvas>

Xaml.cs:

bool isDragging = false;
double x = 0;
double y = 0;

private void Border_MouseEnter(object sender, MouseEventArgs e)
{
    if(isDragging)
        Title = "Captured";
}

private void Thumb_DragStarted(object sender, System.Windows.Controls.Primitives.DragStartedEventArgs e)
{
    isDragging = true;
    x = e.HorizontalOffset;
    y = e.VerticalOffset;
}

private void Thumb_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
{
    isDragging = false;
}

private void Thumb_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
{
    x += e.HorizontalChange;
    y += e.VerticalChange;
    dragTarget.Margin = new Thickness(x , y , 0, 0);
}

Upvotes: 3

Views: 1549

Answers (1)

Lee Louviere
Lee Louviere

Reputation: 5262

Mouse is captured while dragging, so you probably won't get the message.

In the Thumb_DragDelta event, get the mouse location using the border. It will be relative to the border. Check to see if the mouse point is within the border.

Point point = Mouse.GetPosition(border);

Rect rect = new Rect(0, 0, border.ActualWidth, border.ActualHeight);
Boolean mouseInBorder = rect.Contains(point);

if (mouseInBorder && !mouseLastInBorder)
{
    // Mouse enter "event";
}
if (!mouseInBorder && mouseLastInBorder)
{
    // Mouse exit "event";
}
mouseLastInBorder = mouseInBorder;

Upvotes: 1

Related Questions