鼠标光标附近的WPF Flink 弹出窗口

f0ofjuux  于 2023-10-22  发布在  Flink
关注(0)|答案(2)|浏览(236)

我尝试在鼠标光标旁边显示一个WPF弹出窗口。窗口位置将在鼠标移动事件期间更新。主窗口是这样的:

<Grid x:Name="_layoutGrid" Background="Transparent">
    <DockPanel Background="Green"/>
    <Popup Name="_cursorInfo" 
           IsHitTestVisible="False"
           AllowsTransparency="True" 
           Placement="Relative" 
           PlacementTarget="{Binding ElementName=_layoutGrid}">
        <Border CornerRadius="1" Padding="1" Background="Blue" Opacity="0.7" IsHitTestVisible="False">
            <TextBlock Text="Here is a content" IsHitTestVisible="False" />
        </Border>
    </Popup>
</Grid>

鼠标移动的事件处理程序如下所示:

public MainWindow()
    {
        InitializeComponent();
        _layoutGrid.MouseMove += LayoutGrid_MouseMove;
        _layoutGrid.MouseLeave += LayoutGrid_MouseLeave;
    }
    private void LayoutGrid_MouseLeave(object sender, MouseEventArgs e)
    {
        _cursorInfo.IsOpen = false;
    }

    private void LayoutGrid_MouseMove(object sender, MouseEventArgs e)
    {
        var pos = e.GetPosition(_layoutGrid);
        if (!_cursorInfo.IsOpen)
        {
            _cursorInfo.IsOpen = true;
        }
        _cursorInfo.HorizontalOffset = pos.X;
        _cursorInfo.VerticalOffset = pos.Y;
        Debug.WriteLine($"Pos: {pos}");
    }

弹出窗口显示出来,但有很多“ Flink ”。似乎鼠标在弹出窗口中被短暂捕获,导致 Flink 。我还认识到,当我删除包含边界的背景时, Flink 消失了。但是,我想看到一个彩色背景的边界。我以为设置“IsHitTestVisible”就足够了,但似乎我错了。有什么办法可以避免 Flink 吗?

isr3a4wc

isr3a4wc1#

Flink 可能是由LayoutGrid_MouseLeave中关闭Popup的代码引起的。您需要在此事件处理程序中添加一些额外的检查,以验证鼠标指针相对于Grid的实际位置,例如:

private void LayoutGrid_MouseLeave(object sender, MouseEventArgs e)
{
    Point p = Mouse.GetPosition(_layoutGrid);
    if (p.X >= 0 && p.Y >= 0 && p.X <= _layoutGrid.ActualWidth && p.Y <= _layoutGrid.ActualHeight)
        return;

    _cursorInfo.IsOpen = false;
}
jaxagkaj

jaxagkaj2#

添加一些额外的偏移到光标的X和Y位置,它似乎解决了这个问题

_cursorInfo.HorizontalOffset = pos.X + 10;
_cursorInfo.VerticalOffset = pos.Y + 10;

相关问题