是否有人知道可以执行此类操作的免费或商业WPF控件:
每盒X个字符,并在完成每个方框时自动切换到下一个方框?与为Microsoft产品输入许可证密钥的方式类似。
我认为从头开始做起来并不是特别困难,但如果已经存在一个很好的例子,我想避免重新发明轮子。
答案 0 :(得分:4)
WPF提供您所需要的一切,除了自动切换到下一个控件。行为可以提供该功能,结果如下所示:
<Grid>
<Grid.Resources>
<local:KeyTextCollection x:Key="keys"/>
</Grid.Resources>
<StackPanel>
<ItemsControl ItemsSource="{StaticResource keys}" Focusable="False">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" Background="AliceBlue"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Text}" Margin="5" MaxLength="4" Width="40">
<i:Interaction.Behaviors>
<local:TextBoxBehavior AutoTab="True" SelectOnFocus="True"/>
</i:Interaction.Behaviors>
</TextBox>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Grid>
以下是KeyText和KeyTextCollection类(根据品味调整):
class KeyText
{
public string Text { get; set; }
}
class KeyTextCollection : List<KeyText>
{
public KeyTextCollection()
{
for (int i = 0; i < 4; i++) Add(new KeyText { Text = "" });
}
}
这是实现自动选项卡和选择焦点的行为:
public class TextBoxBehavior : Behavior<TextBox>
{
public bool SelectOnFocus
{
get { return (bool)GetValue(SelectOnFocusProperty); }
set { SetValue(SelectOnFocusProperty, value); }
}
public static readonly DependencyProperty SelectOnFocusProperty =
DependencyProperty.Register("SelectOnFocus", typeof(bool), typeof(TextBoxBehavior), new UIPropertyMetadata(false));
public bool AutoTab
{
get { return (bool)GetValue(AutoTabProperty); }
set { SetValue(AutoTabProperty, value); }
}
public static readonly DependencyProperty AutoTabProperty =
DependencyProperty.Register("AutoTab", typeof(bool), typeof(TextBoxBase), new UIPropertyMetadata(false));
protected override void OnAttached()
{
AssociatedObject.PreviewGotKeyboardFocus += (s, e) =>
{
if (SelectOnFocus)
{
Action action = () => AssociatedObject.SelectAll();
AssociatedObject.Dispatcher.BeginInvoke(action, DispatcherPriority.ContextIdle);
}
};
AssociatedObject.TextChanged += (s, e) =>
{
if (AutoTab)
{
if (AssociatedObject.Text.Length == AssociatedObject.MaxLength &&
AssociatedObject.SelectionStart == AssociatedObject.MaxLength)
{
AssociatedObject.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
}
};
}
}
如果您不熟悉行为,请安装Expression Blend 4 SDK并添加此命名空间:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
并将System.Windows.Interactivity
添加到您的项目中。