Mittwoch, 26. Mai 2010

WPF - SelectAll() OnFocus Behavior für TextBox

Einfaches Behavior für die SelectAll() Funktionalität bei Focus für eine TextBox in Wpf.

public class TextBoxSelectAllOnFocusBehavior : Behavior<TextBox>
{
    /// <summary>
    /// SelectAll auch wenn nur leerzeichen in der TextBox stehen
    /// </summary>
    public bool SelectedAllOnWhitespace { getset; }
 
    public TextBoxSelectAllOnFocusBehavior()
    {
        this.SelectedAllOnWhitespace = true;
    }
 
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.GotKeyboardFocus += AssociatedObjectGotKeyboardFocus;
    }
 
    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.GotKeyboardFocus -= AssociatedObjectGotKeyboardFocus;
    }
 
    private void AssociatedObjectGotKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e)
    {
        if (this.SelectedAllOnWhitespace)
            AssociatedObject.SelectAll();
        else
        {
            if (!string.IsNullOrWhiteSpace(AssociatedObject.Text))
                AssociatedObject.SelectAll();
        }
    }
 
}

Im Xaml sieht das ganze dann so aus.

Keine Kommentare:

Kommentar veröffentlichen