WPF_實現點擊文本框外部時失去焦點


首先在XAML界面隨便放一個Text Box(文本框控件),

然后在窗口添加一個MouseDown事件(鼠標按下事件)

代碼如下:

<Window x:Class="WpfApp1.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"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800"
        MouseDown="window_MouseDown"><!--在窗口添加一個MouseDowm(鼠標按下)事件-->
    <Grid Background="#FFC1C1C1">
        <TextBox Margin="10,10,10,360" BorderBrush="Black"></TextBox>
    </Grid>
</Window>

在XAML添加MouseDowm事件后,在后台會自動生成一個MouseDowm方法,在方法里添加   Keyboard.ClearFocus();  一句代碼就好了

using System.Windows;
using System.Windows.Input;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Keyboard.ClearFocus();//Keyboard.ClearFocus 方法    清除焦點
        }
    }
}

 

 

 

 

 


免責聲明!

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



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