All pastes #1433965 Raw Edit

Select-all-on-focus attached beh

public text v1 · immutable
#1433965 ·published 2009-05-25 15:00 UTC
rendered paste body
public static class TextBoxBehavior
{
	public static bool GetSelectAllOnFocus(DependencyObject obj)
	{
		return (bool)obj.GetValue(SelectAllOnFocusProperty);
	}

	public static void SetSelectAllOnFocus(DependencyObject obj, bool value)
	{
		obj.SetValue(SelectAllOnFocusProperty, value);
	}

	public static readonly DependencyProperty SelectAllOnFocusProperty =
		DependencyProperty.RegisterAttached(
			"SelectAllOnFocus", 
			typeof(bool), 
			typeof(TextBoxBehavior), 
			new UIPropertyMetadata(false, OnSelectAllOnFocusChanged)
		);

	private static void OnSelectAllOnFocusChanged(
		DependencyObject depObj, 
		DependencyPropertyChangedEventArgs e)
	{
		TextBox textBox = depObj as TextBox;

		if (textBox != null && e.NewValue is bool)
		{
			if ((bool)e.NewValue)
				textBox.GotFocus += TextBox_SelectAllOnFocus;
			else
				textBox.GotFocus -= TextBox_SelectAllOnFocus;
		}
	}

	private static void TextBox_SelectAllOnFocus(object sender, RoutedEventArgs e)
	{
		(sender as TextBox).SelectAll();
	}
}