一个常见的需求是,用户在某个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.Interactivityimports System.windows.Dataimports System.windows.automation.Peersimports System.windows.automation.ProvIDerimports 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 @R_301_5983@Txts = Associatedobject.Children.OfType(Of TextBox)() For Each txt In @R_301_5983@Txts Dim exp As BindingExpression = txt.GetBindingExpression(TextBox.TextProperty) exp.UpdateSource() Next 'update binding source of Password Dim @R_301_5983@Pwds = Associatedobject.Children.OfType(Of PasswordBox)() For Each pwd In @R_301_5983@Pwds 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总结
以上是内存溢出为你收集整理的Silverlight - 回车键触发默认按钮全部内容,希望文章能够帮你解决Silverlight - 回车键触发默认按钮所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)