1. 程式人生 > >【WPF】獲取焦點全部選中事件

【WPF】獲取焦點全部選中事件

效果

在這裡插入圖片描述

功能

當TextBox獲取焦點時,如TextBox中有內容,則預設全部選中

程式碼

public AddTaskWindow()
{
    InitializeComponent();
    //在文字框獲取焦點時,要求其中內容全部選中
    txtContent.PreviewMouseDown += new MouseButtonEventHandler(txtContent_PreviewMouseDown);
    txtContent.GotFocus += new RoutedEventHandler(txtContent_GotFocus);
    txtContent.LostFocus += new RoutedEventHandler(txtContent_LostFocus);
}

/// <summary>
/// 番茄名稱,獲取焦點
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txtContent_GotFocus(object sender, RoutedEventArgs e)
{
    txtContent.SelectAll();//全選
    txtContent.PreviewMouseDown -= new MouseButtonEventHandler(txtContent_PreviewMouseDown);   
}

/// 番茄名稱,失去焦點
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txtContent_LostFocus(object sender, RoutedEventArgs e)
{
    txtContent.PreviewMouseDown += new MouseButtonEventHandler(txtContent_PreviewMouseDown);
}

/// <summary>
/// 番茄名稱,單擊事件前
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txtContent_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    txtContent.Focus();
    e.Handled = true;
}