- WPF 教程
- WPF - 主页
- WPF - 概述
- WPF - 环境设置
- WPF - Hello World
- WPF - XAML 概述
- WPF - 元素树
- WPF - 依赖属性
- WPF - 路由事件
- WPF - 控件
- WPF - 布局
- WPF - 布局嵌套
- WPF - 输入
- WPF - 命令行
- WPF - 数据绑定
- WPF - 资源
- WPF - 模板
- WPF - 样式
- WPF - 触发器
- WPF - 调试
- WPF - 自定义控件
- WPF - 异常处理
- WPF - 本地化
- WPF - 交互
- WPF - 2D 图形
- WPF - 3D 图形
- WPF - 多媒体
- WPF 有用资源
- WPF - 快速指南
- WPF - 有用资源
- WPF - 讨论
WPF - 鼠标
有多种类型的鼠标输入,如 MouseDown、MouseEnter、MouseLeave 等。在以下示例中,我们将处理一些鼠标输入。
让我们创建一个新的 WPF 项目,名为 WPFMouseInput。
将一个矩形和三个文本块拖到堆栈面板,并设置以下属性和事件,如以下 XAML 文件所示。
<Window x:Class = "WPFMouseInput.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local = "clr-namespace:WPFMouseInput" mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604"> <StackPanel> <Rectangle x:Name = "mrRec" Fill = "AliceBlue" MouseEnter = "OnMouseEnter" MouseLeave = "OnMouseLeave" MouseMove = "OnMouseMove" MouseDown = "OnMouseDown" Height = "100" Margin = "20"> </Rectangle> <TextBlock x:Name = "txt1" Height = "31" HorizontalAlignment = "Right" Width = "250" Margin = "0,0,294,0" /> <TextBlock x:Name = "txt2" Height = "31" HorizontalAlignment = "Right" Width = "250" Margin = "0,0,294,0" /> <TextBlock x:Name = "txt3" Height = "31" HorizontalAlignment = "Right" Width = "250" Margin = "0,0,294,0" /> </StackPanel> </Window>
以下是处理不同鼠标事件的 C# 代码。
using System.Windows; using System.Windows.Input; using System.Windows.Media; using System.Windows.Shapes; namespace WPFMouseInput { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void OnMouseEnter(object sender, MouseEventArgs e) { Rectangle source = e.Source as Rectangle; if (source != null) { source.Fill = Brushes.SlateGray; } txt1.Text = "Mouse Entered"; } private void OnMouseLeave(object sender, MouseEventArgs e) { // Cast the source of the event to a Button. Rectangle source = e.Source as Rectangle; // If source is a Button. if (source != null) { source.Fill = Brushes.AliceBlue; } txt1.Text = "Mouse Leave"; txt2.Text = ""; txt3.Text = ""; } private void OnMouseMove(object sender, MouseEventArgs e) { Point pnt = e.GetPosition(mrRec); txt2.Text = "Mouse Move: " + pnt.ToString(); } private void OnMouseDown(object sender, MouseButtonEventArgs e) { Rectangle source = e.Source as Rectangle; Point pnt = e.GetPosition(mrRec); txt3.Text = "Mouse Click: " + pnt.ToString(); if (source != null) { source.Fill = Brushes.Beige; } } } }
编译并执行上述代码时,将产生以下窗口 −
当鼠标进入矩形内时,矩形的颜色会自动改变。此外,您将看到一条消息,表明鼠标已进入,并显示其坐标。
当您在矩形内单击时,它会改变颜色,并显示鼠标单击的坐标。
当鼠标离开矩形时,它将显示鼠标已离开的消息,矩形将变为其默认颜色。
wpf_input.htm
广告