Pregunta

I have some concept question here. I know how to select all text in TextBox or in PasswordBox. Via GotKeyboardFocus and PreviewMouseLeftButtonDown events, you know. This works fine.

XAML:

PreviewMouseLeftButtonDown="PasswordOnPreviewMouseDown"
GotKeyboardFocus="SelectAllPassword"

CodeBehind

private void SelectAllPassword(Object sender, RoutedEventArgs e)
{
    var pb = (sender as PasswordBox);
    if (pb != null)
        pb.SelectAll();
}

private void PasswordOnPreviewMouseDown(Object sender, MouseButtonEventArgs e)
{
    var pb = (sender as PasswordBox);
    if (pb != null)
        if (!pb.IsKeyboardFocusWithin)
        {
            e.Handled = true;
            pb.Focus();
        }
}

But question is - why this doesn't work?

XAML:

PreviewMouseLeftButtonDown="PasswordOnPreviewMouseDown"

CodeBehind:

private void PasswordOnPreviewMouseDown(Object sender, MouseButtonEventArgs e)
{
    _txtPassword.SelectAll();
    e.Handled = true;
}

Where _txtPassword - TextBox or PasswordBox control. So why I'm enforsed to Focus text control?

¿Fue útil?

Solución

Actually, the selection is working.

You may feel that the text is not selected because it's not visually highlighted, but that's because the TextBox is not focused.

Try giving focus to your TextBox with the Tab key, you'll see the whole text highlighted.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top