martedì 3 maggio 2011

Selezionare il contenuto di una TextBox al Focus

Link originale: http://stackoverflow.com/questions/660554/how-to-automatically-select-all-text-on-focus-in-wpf-textbox.

La modifica consiste nell’includere il comportamento come un behavior. Ecco il codice:
 
public static class TextBoxBehaviors
{
    public static void SetSelectOnFocus(UIElement element, Boolean value)
    {
        element.SetValue(SelectOnFocusProperty, value);
    }
    public static bool GetSelectOnFocus(UIElement element)
    {
        return (bool)element.GetValue(SelectOnFocusProperty);
    }
    public static readonly DependencyProperty SelectOnFocusProperty =
        DependencyProperty.RegisterAttached("SelectOnFocus", typeof(bool), typeof(TextBoxBehaviors),
        new FrameworkPropertyMetadata(false, SelectOnFocusPropertyChangedCallback));

    private static void SelectOnFocusPropertyChangedCallback(DependencyObject depObj, DependencyPropertyChangedEventArgs eventArgs)
    {
        TextBox tb = depObj as TextBox;
        if (tb != null)
        {
            if ((bool)eventArgs.OldValue == false && (bool)eventArgs.NewValue == true)
            {
                //attach events      
                tb.PreviewMouseLeftButtonDown += SelectivelyIgnoreMouseButton;
                tb.GotKeyboardFocus += SelectAllText;
                tb.MouseDoubleClick += SelectAllText;
            }
            else if ((bool)eventArgs.OldValue == true && (bool)eventArgs.NewValue == false)
            {
                //detach events     
                tb.PreviewMouseLeftButtonDown -= SelectivelyIgnoreMouseButton;
                tb.GotKeyboardFocus -= SelectAllText;
                tb.MouseDoubleClick -= SelectAllText;
            }
        }
    }
    private static void SelectivelyIgnoreMouseButton(object sender, MouseButtonEventArgs e)
    {
        DependencyObject parent = e.OriginalSource as UIElement;
        while (parent != null && !(parent is TextBox))
            parent = VisualTreeHelper.GetParent(parent);

        if (parent != null)
        {
            var textBox = (TextBox)parent;
            if (!textBox.IsKeyboardFocusWithin)
            {
                textBox.Focus();
                e.Handled = true;
            }
        }
    }
    private static void SelectAllText(object sender, RoutedEventArgs e)
    {
        var textBox = e.OriginalSource as TextBox;
        if (textBox != null)
            textBox.SelectAll();
    }
}
 
E’ possibile ora aggiungere nello xaml il comportamento aggiungendo il behavior:
 
<TextBox Text="Selezionami per provare" behaviors:TextBoxBehaviors.SelectOnFocus="True" />