Uncategorized

[WPF] Behavior to focus element when button clicked

Create a new behavior GetFocusBehavior

public class GetFocusBehavior : Behavior
    {
        private ButtonBase _button;
 
        protected override void OnAttached()
        {
            _button = AssociatedObject;
 
            _button.Click += ButtonClick;
        }
 
        protected override void OnDetaching()
        {
            _button.Click -= ButtonClick;
        }
 
        private void ButtonClick(object sender, RoutedEventArgs e)
        {
            Keyboard.Focus(FocusElement);
        }
 
        public Control FocusElement
        {
            get { return (Control) GetValue(FocusElementProperty); }
            set { SetValue(FocusElementProperty, value);}
        }
 
        public static  readonly DependencyProperty FocusElementProperty =
            DependencyProperty.Register("FocusElement",typeof(Control),typeof(GetFocusBehavior), new UIPropertyMetadata());
 
    }

In the View that we want to apply above behavior, we need to add reference on top of that:

xmlns:behaviors="clr-namespace:Weather.Behaviors"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

Add trigger below to activate the behavior

<TextBox Text="{Binding Keyword}"
                     Name="TxtKeyword"
                     Margin="5"
                     Width="100"
                     Height="20"></TextBox>
            <Button Command="{Binding SearchCommand}" 
                    Content="Search" 
                    Margin="5" 
                    Width="50"
                    Height="20"
                    FontSize="10"></Button>
            <Button Command="{Binding ClearCommand}" 
                    Content="Clear" 
                    Margin="5" 
                    Width="50"
                    Height="20"
                    FontSize="10">
                <i:Interaction.Behaviors>
                    <behaviors:GetFocusBehavior FocusElement="{Binding ElementName=TxtKeyword, Mode=OneWay}"/>
                </i:Interaction.Behaviors>
            </Button>

The above behavior will put cursor back on Textbox name TxtKeyword whenever Button is clicked.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s