3

我有一个拇指(包含一个文本块)和一个画布内的边框。Thumb 接收到拖动事件,并且正在正确拖动。

我需要的是在 Thumb 拖动时在 Border 上捕获 MouseEnter 事件。

问题是 MouseEnter 在 DragCompleted 事件之后被触发(在释放鼠标按钮之后)。当鼠标按钮按下时,我如何知道鼠标何时进入边框?

xml:

<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);
}
4

1 回答 1

1

拖动时会捕获鼠标,因此您可能不会收到消息。

在 Thumb_DragDelta 事件中,使用边框获取鼠标位置。它将相对于边界。检查鼠标点是否在边界内。

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;
于 2012-10-05T13:30:51.787 回答