XAML Trigger Auto-tab when reaching MaxLength

How can I enable the automatic tab when the MaxLength property is reached in XAML Trigger, DataTrigger, PropertyTrigger, Style.Trigger, etc. Below are two such parameters, as I already did with the help of TextBox through code-behind. I also want to apply it in XAML style. Thank.

XAML:

<TextBox x:Name="MyTextBox"
            Text="{Binding Path=MyProperty}"
            Style="{StaticResource TextBoxStyle}"
            MaxLength="5"
            TextChanged="MyTextBox_TextChanged">
</TextBox>

Code for WPF:

private void MyTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    if (MyTextBox.Text.Length == MyTextBox.MaxLength)
    {
        Keyboard.Focus(NextTextBox);
    }
}

private void MyTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
    // Auto-tab when maxlength is reached
        if (((TextBox)sender).MaxLength == ((TextBox)sender).Text.Length)
        {
            // move focus
            var ue = e.OriginalSource as FrameworkElement;
            e.Handled = true;
            ue.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }
    }
}
+3
source share
1 answer

just do it in your Shell.xaml

 <Style TargetType="TextBox">
                <EventSetter Event="TextChanged" Handler="MyTextBox_PreviewKeyDown"/>
            </Style>

and in your shell.xaml.cs

private void MyTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
    // Auto-tab when maxlength is reached
        if (((TextBox)sender).MaxLength == ((TextBox)sender).Text.Length)
        {
            // move focus
            var ue = e.OriginalSource as FrameworkElement;
            e.Handled = true;
            ue.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }
    }
}
0
source

Source: https://habr.com/ru/post/1778199/


All Articles