达到 MaxLength 时 XAML 触发器自动选项卡 [英] XAML Trigger Auto-tab when MaxLength is Reached

查看:27
本文介绍了达到 MaxLength 时 XAML 触发器自动选项卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当 MaxLength 属性到达 XAML 触发器、DataTrigger、PropertyTrigger、Style.Trigger 等时,如何将自动选项卡合并.以下是我如何通过代码使用 TextBox 完成此操作的两个此类选项 -在后面.我也希望以 XAML 样式应用它.谢谢.

How can I incorporate an auto-tab when the MaxLength property is reached into a XAML Trigger, DataTrigger, PropertyTrigger, Style.Trigger, etc. Below are two such options for how I have already accomplished this with a TextBox via code-behind. I'm looking to apply it in a XAML style as well. Thanks.

XAML:

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

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));
        }
    }
}

推荐答案

只需在您的 Shell.xaml 中执行此操作

simply do this in your Shell.xaml

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

并在您的 shell.xaml.cs 中

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));
        }
    }
}

这篇关于达到 MaxLength 时 XAML 触发器自动选项卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆