
- 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
廣告