Enter Button Behavior
-
Thursday, April 19, 2012 6:54 PM
Hi, I am using MVVM and would like to know how to create Enter Button Behavior. I need this for a search screen and be nice to just enter search criteria in textbox and hit ENTER instead of clicking the search button. Thanks.
All Replies
-
Friday, April 20, 2012 2:45 AM
Here's what I use:
Imports System.Windows.Interactivity Namespace Behaviors Public Class TextBoxUpdateBehavior : Inherits Behavior(Of TextBox) Public Sub New() End Sub Protected Overrides Sub OnAttached() MyBase.OnAttached() AddHandler AssociatedObject.TextChanged, AddressOf AssociatedObjectOnTextChanged End Sub Private Sub AssociatedObjectOnTextChanged(sender As Object, args As TextChangedEventArgs) Dim bindingExpr = AssociatedObject.GetBindingExpression(TextBox.TextProperty) bindingExpr.UpdateSource() End Sub Protected Overrides Sub OnDetaching() MyBase.OnDetaching() RemoveHandler AssociatedObject.TextChanged, AddressOf AssociatedObjectOnTextChanged End Sub End Class End NamespaceGraeme
-
Friday, April 20, 2012 6:24 PM
Hi, thanks for the reply, I'll have to translate it to C#. How does it know which button to initiate the click on?
-
Friday, April 20, 2012 9:12 PM
It fires a number of events that normally don't fire in MVVM. Here's how I hook up the textbox
<TextBox Text="{Binding NewText, Mode=TwoWay}"> <i:Interaction.Behaviors> <behaviors:TextBoxUpdateBehavior/> </i:Interaction.Behaviors> <i:Interaction.Triggers> <i:EventTrigger EventName="KeyUp"> <cmd:EventToCommand Command="{Binding KeyUpCommand}" PassEventArgsToCommand="True"/> </i:EventTrigger> </i:Interaction.Triggers> </TextBox>Then in the Codebehind (I use MVVMLight for Commands)
Public ReadOnly Property KeyUpCommand As RelayCommand(Of KeyEventArgs) Get Return New RelayCommand(Of KeyEventArgs)(Sub(e) If e.Key = Key.Enter Then ' call the code that button would normally End If End Sub) End Get End PropertyGraeme
-
Saturday, April 21, 2012 4:45 PM
Thanks, I will go ahead and give it a shot now.

