[WPF]實現TextBox文字框單擊全選
/// <summary>
/// Void:設定獲取焦點時全選文字
/// </summary>
/// <param name="textbox">指定文字框</param>
public void SetSelectionAllOnGotFocus(TextBox textbox)
{
MouseButtonEventHandler _OnPreviewMouseDown = (sender, e) =>
{
TextBox box = e.Source as TextBox;
box.Focus();
e.Handled = true;
};
RoutedEventHandler _OnLostFocus = (sender, e) =>
{
TextBox box = e.Source as TextBox;
box.PreviewMouseDown += _OnPreviewMouseDown;
};
RoutedEventHandler _OnGotFocus = (sender, e) =>
{
TextBox box = e.Source as TextBox;
box.SelectAll();
box.PreviewMouseDown -= _OnPreviewMouseDown;
};
textbox.PreviewMouseDown += _OnPreviewMouseDown;
textbox.LostFocus += _OnLostFocus;
textbox.GotFocus += _OnGotFocus;
}