当使用TextBox的PreviewMouseLeftButtonUp事件时(例如,鼠标点击进入TextBox时,清除当前的输入内容),会很意外地发现,这时候不论怎么点击都无法点击到其他控件,焦点一直被文本框占用着。

解决办法及测试用例如下:

界面

 <Window x:Class="learnwpf.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListBox>
<TextBox x:Name="textbox" PreviewMouseLeftButtonUp="textbox_PreviewMouseLeftButtonUp" Text="测试文本" Width="150" Height="30"/>
<Button x:Name="btn" Click="btn_Click" Width="100" Height="30" />
</ListBox>
</Grid>
</Window>

逻辑

 using System.Windows;
using System.Windows.Controls;
using System.Windows.Input; namespace learnwpf
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
} private void btn_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Button's clicked");
} private void textbox_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
textbox.Text = string.Empty;
e.Handled = true;
// 移除TextBox对鼠标的捕获
((TextBox)textbox).ReleaseMouseCapture();
}
}
}
04-25 06:37