一个常见的需求是,用户在某个TextBox中输入回车键,自动触发界面上的某个按钮。比如登录窗口中,用户输入完密码后按回车,自动触发登录按钮。

Silverlight (4.0)目前还没有像winform程序那样可通过设置一个属性值来简单实现。
Patrick Cauldweel 提供了一个方案, Kyle Burns 做了些改进,增加了通用性,并解决了前者的一些缺点。
受Kyle启发,我的实现方法是实现为一个Panel(Grid,Canvas,StackPanel的基类)控件的Behavior。该实现需要引用System.Windows.Interactivity.dll
一个示例登录窗口的Xaml如下:
<StackPanel>
<i:Interaction.Behaviors>
<command:DefaultButtonBehaviorDefaultButtonName="{BindingElementName=btnLogin,Path=Name}"/>
</i:Interaction.Behaviors>
<TextBox Text="{Binding LoginName}"/>
<PasswordBox Password="{Binding LoginPassword}"/>
<Button Content="Login" x:Name="btnLogin" Command="{Binding LoginCommand}"/>
</StackPanel>
DefaultButtonBehavior类(vb.net):
ImportsSystem.Windows.Interactivity ImportsSystem.Windows.Data ImportsSystem.Windows.Automation.Peers ImportsSystem.Windows.Automation.Provider ImportsSystem.Linq NamespaceCommands PublicClassDefaultButtonBehavior InheritsBehavior(OfPanel) PublicPropertyDefaultButtonNameAsString Get ReturnCType(GetValue(DefaultButtonNameProperty),String) EndGet Set(ByValvalueAsString) SetValue(DefaultButtonNameProperty,value) EndSet EndProperty PublicSharedReadOnlyDefaultButtonNamePropertyAsDependencyProperty_ =DependencyProperty.Register(name:="DefaultButtonName",_ propertyType:=GetType(String),_ ownerType:=GetType(DefaultButtonBehavior),_ typeMetadata:=Nothing) ProtectedOverridesSubOnAttached() MyBase.OnAttached() AddHandlerAssociatedObject.KeyUp,AddressOfAssociatedObject_KeyUp EndSub ProtectedOverridesSubOnDetaching() MyBase.OnDetaching() RemoveHandlerAssociatedObject.KeyUp,AddressOfAssociatedObject_KeyUp EndSub PrivateSubAssociatedObject_KeyUp(ByValsenderAsObject,ByValeAsKeyEventArgs) Ife.Key=Key.EnterThen DimdefaultButtonAsButton=AssociatedObject.Children.OfType(OfButton).FirstOrDefault(Function(x)x.Name=DefaultButtonName) IfdefaultButtonIsNotNothingAnddefaultButton.IsEnabledThen 'updatebindingsourceofTextBox DiminputTxts=AssociatedObject.Children.OfType(OfTextBox)() ForEachtxtIninputTxts DimexpAsBindingExpression=txt.GetBindingExpression(TextBox.TextProperty) exp.UpdateSource() Next 'updatebindingsourceofPassword DiminputPwds=AssociatedObject.Children.OfType(OfPasswordBox)() ForEachpwdIninputPwds DimexpAsBindingExpression=pwd.GetBindingExpression(PasswordBox.PasswordProperty) exp.UpdateSource() Next DimpeerAsNewButtonAutomationPeer(defaultButton) DiminvokeAsIInvokeProvider=peer.GetPattern(PatternInterface.Invoke) invoke.Invoke() e.Handled=True EndIf EndIf EndSub EndClass EndNamespace
本文介绍了一种在Silverlight应用中实现用户输入回车键自动触发指定按钮的方法。通过使用Behavior特性并结合依赖属性,可以轻松地将此行为应用于任何继承自Panel的控件上,如Grid或StackPanel。示例代码展示了如何在一个登录界面中实现这一功能。
1174

被折叠的 条评论
为什么被折叠?



