gpt4 book ai didi

c# - Wpf 鼠标事件超出用户控件问题的范围

转载 作者:行者123 更新时间:2023-11-30 14:55:07 24 4
gpt4 key购买 nike

我有一个奇怪的问题,我不知道如何解决。

我正在从头开始创建颜色选择器。为此,我创建了一组用户控件并将它们放在一个“主控件”中。

例如,当用户拖动色调选择器时,我会向下、移动和向上操作鼠标(在色调选择器用户控件内)。

就实际移动而言,一个简单的 bool 值指示发生了什么。

//Mouse down
_isDrag = true;

//Mouse Move
if(!_isDrag) return;
//Moving the position indicator shape thingy
//Calculating the hue

//Mouse Up
_isDrag = false;

但是,如果鼠标松开发生在色调选择器的边界之外,则不会触发鼠标松开事件。因此,当用户返回到色调选择器的区域时,形状指示器就会运行起来。

我确信某个地方有答案,但恐怕我的搜索技巧无法胜任这项任务。我不知道要寻找什么。

感谢您的宝贵时间。

解决方法:

private bool _isDrag;

//Request Mouse capture for the Container
private void MsDown(object sender, MouseButtonEventArgs e)
{
_isDrag = true;
Mouse.Capture(MainContainer);
}

//Release Mouse capture
private void MsUp(object sender, MouseButtonEventArgs e)
{
_isDrag = false;
Mouse.Capture(null);
}

//Move the handle vertically along the main container, with respect to it's width - so it's centered.
private void MsMove(object sender, MouseEventArgs e)
{
if (!_isDrag) return;
Canvas.SetTop(Handle, e.GetPosition(ContentRow).Y - Handle.ActualHeight / 2);
}

谢谢您的回答!

编辑 2:

跟进我的问题。虽然 Capture 基本上可以解决问题,但我注意到,如果快速拖动到用户控件的边界之外,有时 handle 会卡在边缘附近。如果我慢慢移动鼠标,就不会发生这种情况。诡异的。另外,我永远无法达到 0 和 .ActualHeight

所以我会在这里发布我的修复,以防其他人遇到这个问题。

我这样拆分我的网格:

<Grid.ColumnDefinitions>
<ColumnDefinition Width="7"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="7"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="7"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="7"></RowDefinition>
</Grid.RowDefinitions>

7 是我 handle 的一半大小(一个圆圈)。

内容区域(您可以进行视觉交互的实际区域)位于中间单元格中(在具有错误 HitTest 可见性的单独网格中)。

跨越整个主网格的是一个不可见的矩形,用于 HitTest 。

并移动 handle

        private void MoveHandle()
{
_pos.X = _pos.X - Handle.ActualWidth/2;
_pos.Y = _pos.Y - Handle.ActualHeight / 2;
//this is just to be sure. I'm paranoid. Being a color picker, these actually matter a lot.
_pos.X = Math.Max(Math.Min(_pos.X, RectColor.ActualWidth - Handle.ActualWidth/2), -Handle.ActualWidth / 2);
_pos.Y = Math.Max(Math.Min(_pos.Y, RectColor.ActualHeight -Handle.ActualWidth/2), -Handle.ActualHeight/2);

Canvas.SetLeft(Handle, _pos.X);
Canvas.SetTop(Handle, _pos.Y);
}

我不知道为什么我以前的代码几乎能工作。基本上和以前一样。但是,不知何故,它的性能要好一百万倍。祝你好运!

最佳答案

您要查找的搜索词是Mouse Capture .在您的 MouseDown 中捕获,即使在鼠标离开您的控制后您也可以获得鼠标事件。

关于c# - Wpf 鼠标事件超出用户控件问题的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26081601/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com