- User Name
- Password
- Login button
Here is what I normally do, I write a custom behavior class called DefaultButtonBehavior.
In that class I set TargetButton property to Login button.
using System.Windows; using System.Windows.Automation.Peers; using System.Windows.Automation.Provider;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;
namespace Sample.Behavior
{
public class DefaultButtonBehavior : Behavior<Control>
{
#region Methods
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.KeyDown += PerformKeyDown;
}
protected override void OnDetaching()
{
base.OnDetaching();
this.AssociatedObject.KeyDown -= PerformKeyDown;
}
private void PerformKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter && this.TargetButton != null && this.TargetButton.IsEnabled)
{
ButtonAutomationPeer peer = new ButtonAutomationPeer(this.TargetButton);
IInvokeProvider invokeProvider = peer.GetPattern(PatternInterface.Invoke) as IInvokeProvider;
if (invokeProvider != null)
{
peer.SetFocus(); // This is critical to trigger update biding source
invokeProvider.Invoke();
}
}
}
#endregion
#region Properties
public static DependencyProperty TargetButtonProperty = DependencyProperty.RegisterAttached("TargetButton", typeof(Button), typeof(DefaultButtonBehavior), null);
public Button TargetButton
{
get { return (Button)this.GetValue(TargetButtonProperty); }
set { this.SetValue(TargetButtonProperty, value); }
}
#endregion
}
}
In the PerformKeyDown method, there is the code peer.SetFocus(); this statement is very critical. When you use MVVM, text User name or Password received update value when the TextBox control lost focus. This code statement will set focus to the Login button.
Here is how I will use this in DefaultButtonBehavior Xaml
<Window
. . .
xmlns:behavior="clr-namespace:Sample.Behavior"
Title="Login">
<Grid>
. . .
<TextBox Text="UserName" Width="150">
<i:Interaction.Behaviors>
<behavior:DefaultButtonBehavior TargetButton="{Binding ElementName=LoginButton}"/>
</i:Interaction.Behaviors>
</TextBox>
. . .
<PasswordBox Text="Password" Width="150">
<i:Interaction.Behaviors>
<behavior:DefaultButtonBehavior TargetButton="{Binding ElementName=LoginButton}"/>
</i:Interaction.Behaviors>
</PasswordBox>
. . .
<Button x:Name="LoginButton" Content="Login" Height="25" Width="75" />
</Grid>
</Window>