一个常见的需求是,用户在某个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:DefaultButtonBehavior DefaultButtonName="{Binding ElementName=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):
Imports System.Windows.Interactivity Imports System.Windows.Data Imports System.Windows.Automation.Peers Imports System.Windows.Automation.Provider Imports System.Linq Namespace Commands Public Class DefaultButtonBehavior Inherits Behavior(Of Panel) Public Property DefaultButtonName As String Get Return CType(GetValue(DefaultButtonNameProperty), String) End Get Set(ByVal value As String) SetValue(DefaultButtonNameProperty, value) End Set End Property Public Shared ReadOnly DefaultButtonNameProperty As DependencyProperty _ = DependencyProperty.Register(name:="DefaultButtonName", _ propertyType:=GetType(String), _ ownerType:=GetType(DefaultButtonBehavior), _ typeMetadata:=Nothing) Protected Overrides Sub OnAttached() MyBase.OnAttached() AddHandler AssociatedObject.KeyUp, AddressOf AssociatedObject_KeyUp End Sub Protected Overrides Sub OnDetaching() MyBase.OnDetaching() RemoveHandler AssociatedObject.KeyUp, AddressOf AssociatedObject_KeyUp End Sub Private Sub AssociatedObject_KeyUp(ByVal sender As Object, ByVal e As KeyEventArgs) If e.Key = Key.Enter Then Dim defaultButton As Button = AssociatedObject.Children.OfType(Of Button).FirstOrDefault(Function(x) x.Name = DefaultButtonName) If defaultButton IsNot Nothing And defaultButton.IsEnabled Then 'update binding source of TextBox Dim inputTxts = AssociatedObject.Children.OfType(Of TextBox)() For Each txt In inputTxts Dim exp As BindingExpression = txt.GetBindingExpression(TextBox.TextProperty) exp.UpdateSource() Next 'update binding source of Password Dim inputPwds = AssociatedObject.Children.OfType(Of PasswordBox)() For Each pwd In inputPwds Dim exp As BindingExpression = pwd.GetBindingExpression(PasswordBox.PasswordProperty) exp.UpdateSource() Next Dim peer As New ButtonAutomationPeer(defaultButton) Dim invoke As IInvokeProvider = peer.GetPattern(PatternInterface.Invoke) invoke.Invoke() e.Handled = True End If End If End Sub End Class End Namespace