[英]Wpf Mouse Events outside the bounds of a user control issue
我有一個奇怪的問題,我不知道如何解決。
我正在從頭開始創建一個顏色選擇器。 我是通過創建一組用戶控件並將它們放在一個“主控件”中來實現的。
例如,當用戶拖動色調選擇器時,我將鼠標向下移動,向上移動(在色調選擇器用戶控件內)。
一個簡單的布爾決定了發生了什么,就實際移動而言。
//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基本上完成了這個技巧,但我注意到,如果快速拖動到用戶控件的邊界之外,有時手柄會卡在靠近邊緣的位置。 如果我慢慢移動鼠標,就不會發生這種情況。 奇怪的。 此外,我永遠無法達到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是我手柄的一半(圓圈)。
內容區域(您可以在視覺上與之交互的實際區域)位於中間單元格中(在具有錯誤命中測試可見性的單獨網格中)。
跨越整個主網格是一個用於命中測試的不可見矩形。
並移動手柄
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中捕獲,即使鼠標離開您的控件也可以獲得鼠標事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.