达到MaxLength时的XAML触发器自动选项卡

时间:2010-12-02 22:00:02

标签: wpf xaml datatrigger maxlength

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

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

1 个答案:

答案 0 :(得分:0)

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

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

并在你的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));
        }
    }
}