单击并拖动WPF中的选择框
是否可以在WPF中实现鼠标单击和拖动选择框。 是否应该通过简单地绘制矩形,计算其点的坐标和评估此框内其他对象的位置来完成? 还是有其他方法吗?
你能给一些示例代码或链接吗?
以下是我过去用于绘制拖动选择框的简单技术的示例代码。
XAML:
C#:
public partial class Window1 : Window { public Window1() { InitializeComponent(); } bool mouseDown = false; // Set to 'true' when mouse is held down. Point mouseDownPos; // The point where the mouse button was clicked down. private void Grid_MouseDown(object sender, MouseButtonEventArgs e) { // Capture and track the mouse. mouseDown = true; mouseDownPos = e.GetPosition(theGrid); theGrid.CaptureMouse(); // Initial placement of the drag selection box. Canvas.SetLeft(selectionBox, mouseDownPos.X); Canvas.SetTop(selectionBox, mouseDownPos.Y); selectionBox.Width = 0; selectionBox.Height = 0; // Make the drag selection box visible. selectionBox.Visibility = Visibility.Visible; } private void Grid_MouseUp(object sender, MouseButtonEventArgs e) { // Release the mouse capture and stop tracking it. mouseDown = false; theGrid.ReleaseMouseCapture(); // Hide the drag selection box. selectionBox.Visibility = Visibility.Collapsed; Point mouseUpPos = e.GetPosition(theGrid); // TODO: // // The mouse has been released, check to see if any of the items // in the other canvas are contained within mouseDownPos and // mouseUpPos, for any that are, select them! // } private void Grid_MouseMove(object sender, MouseEventArgs e) { if (mouseDown) { // When the mouse is held down, reposition the drag selection box. Point mousePos = e.GetPosition(theGrid); if (mouseDownPos.X < mousePos.X) { Canvas.SetLeft(selectionBox, mouseDownPos.X); selectionBox.Width = mousePos.X - mouseDownPos.X; } else { Canvas.SetLeft(selectionBox, mousePos.X); selectionBox.Width = mouseDownPos.X - mousePos.X; } if (mouseDownPos.Y < mousePos.Y) { Canvas.SetTop(selectionBox, mouseDownPos.Y); selectionBox.Height = mousePos.Y - mouseDownPos.Y; } else { Canvas.SetTop(selectionBox, mousePos.Y); selectionBox.Height = mouseDownPos.Y - mousePos.Y; } } } }
通过添加InkCanvas并将其EditingMode设置为Select,您可以非常轻松地获得此function。 虽然它主要用于Tablet PC墨水的收集和渲染,但它很容易用作基本的设计器表面。
上述就是C#学习教程:单击并拖动WPF中的选择框分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注---计算机技术网(www.ctvol.com)!
MouseDown逻辑:
MouseRect.X = mousePos.X >= MouseStart.X ? MouseStart.X : mousePos.X; MouseRect.Y = mousePos.Y >= MouseStart.Y ? MouseStart.Y : mousePos.Y; MouseRect.Width = Math.Abs(mousePos.X - MouseStart.X); MouseRect.Height = Math.Abs(mousePos.Y - MouseStart.Y);
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1013029.html