当使用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 }