WPF中TextBox的PreviewMouseLeftButtonUp事件


當使用TextBox的PreviewMouseLeftButtonUp事件時(例如,鼠標點擊進入TextBox時,清除當前的輸入內容),會很意外地發現,這時候不論怎么點擊都無法點擊到其他控件,焦點一直被文本框占用着。

解決辦法及測試用例如下:

界面

 1 <Window x:Class="learnwpf.MainWindow"
 2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4         Title="MainWindow" Height="350" Width="525">
 5     <Grid>
 6         <ListBox>
 7             <TextBox x:Name="textbox" PreviewMouseLeftButtonUp="textbox_PreviewMouseLeftButtonUp" Text="測試文本" Width="150" Height="30"/>
 8             <Button x:Name="btn" Click="btn_Click" Width="100" Height="30" />
 9         </ListBox>
10     </Grid>
11 </Window>

邏輯

 1 using System.Windows;
 2 using System.Windows.Controls;
 3 using System.Windows.Input;
 4 
 5 namespace learnwpf
 6 {
 7     /// <summary>
 8     /// Interaction logic for MainWindow.xaml
 9     /// </summary>
10     public partial class MainWindow : Window
11     {
12         public MainWindow()
13         {
14             InitializeComponent();
15         }
16 
17         private void btn_Click(object sender, RoutedEventArgs e)
18         {
19             MessageBox.Show("Button's clicked");
20         }
21 
22         private void textbox_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
23         {
24             textbox.Text = string.Empty;
25             e.Handled = true;
26             // 移除TextBox對鼠標的捕獲
27             ((TextBox)textbox).ReleaseMouseCapture();
28         }
29     }
30 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM