WPF框选实例代码及程序分享
以下是一个简单的 WPF 框选示例代码和程序的示例,使用 C# 编写。该示例演示如何使用鼠标绘制矩形并选择窗口中的项目。
示例代码:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
private Point startPoint;
private Rectangle rect;
private bool isDragging;
public MainWindow()
{
InitializeComponent();
}
private void canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
startPoint = e.GetPosition(canvas);
rect = new Rectangle
{
Stroke = Brushes.LightBlue,
StrokeThickness = 2,
Fill = Brushes.Transparent
};
Canvas.SetLeft(rect, startPoint.X);
Canvas.SetTop(rect, startPoint.Y);
canvas.Children.Add(rect);
isDragging = true;
}
private void canvas_MouseMove(object sender, MouseEventArgs e)
{
if (!isDragging)
return;
var pos = e.GetPosition(canvas);
var x = Math.Min(pos.X, startPoint.X);
var y = Math.Min(pos.Y, startPoint.Y);
var w = Math.Max(pos.X, startPoint.X) - x;
var h = Math.Max(pos.Y, startPoint.Y) - y;
rect.Width = w;
rect.Height = h;
Canvas.SetLeft(rect, x);
Canvas.SetTop(rect, y);
}
private void canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
isDragging = false;
// Perform selection logic here.
}
}
}
用户评论