Today I tried implementing a Select All-Behavior for Password- and TextBoxes. My initial test with

public class PasswordBoxSelectallBehavior : Behavior<PasswordBox>
{
    protected override void OnAttached()
    {
        base.OnAttached();

        AssociatedObject.GotFocus += AssociatedObject_GotFocus;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();

        AssociatedObject.GotFocus -= AssociatedObject_GotFocus;
    }

    private void AssociatedObject_GotFocus(object sender, System.Windows.RoutedEventArgs e) => AssociatedObject.SelectAll());
}

Did not work as expected. I did research for SelectAll and PasswordBox not working and stumbled over a Microsoft Support Thread suggesting use of a thread to defer the call to SelectAll() which lead me to a experiment:
Instead of a Task or Thread I'd use the general available Dispatcher with InvokeAsync instead of Invoke. This defers the method call into future resulting in enough time for the PasswordBox/TextBox to complete any logic. The result looks like

public class PasswordBoxSelectallBehavior : Behavior<PasswordBox>
{
    protected override void OnAttached()
    {
        base.OnAttached();

        AssociatedObject.GotFocus += AssociatedObject_GotFocus;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();

        AssociatedObject.GotFocus -= AssociatedObject_GotFocus;
    }

    private void AssociatedObject_GotFocus(object sender, System.Windows.RoutedEventArgs e) => Dispatcher.InvokeAsync(AssociatedObject.SelectAll);
}

That's it from me again. Just a quick note for this behavior.

Previous Post Next Post