WPF - Set Focus when a button is clicked - No Code Behind

wpf set focus mvvm
wpf trigger set focus
wpf set focus on textbox
wpf default focus
wpf set keyboard focus xaml
wpf button focus
wpf textbox focus not working
wpf set focus on load

Is there a way to set Focus from one control to another using WPF Triggers?

Like the following example:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Grid>  
    <Grid.RowDefinitions>
      <RowDefinition/>
      <RowDefinition/>
      <RowDefinition/>
    </Grid.RowDefinitions>

    <TextBox Name="txtName"></TextBox>    
    <TextBox Grid.Row="1" Name="txtAddress"></TextBox>
    <Button Grid.Row="2" Content="Finish">
        <Button.Triggers>
            <EventTrigger RoutedEvent="Button.Click">

                <!-- Insert cool code here-->  

            </EventTrigger>
        </Button.Triggers>
    </Button>
  </Grid>
</Page>

Is there a way for this EventTrigger to put to focus on the textBox "txtName"?

I am trying to find the way to do something like this using strict MVVM. If this is something that should not be done via the XAML (in MVVM) then that is fine. But I would like to see some kind of documentation as to how it fit in the MVVM pattern doing it outside the XAML.


Have you considered using an attached behaviour. They are simple to implement and use AttachedProperty's. Although it still requires code, this code is abstracted away in a class and be reused. They can eliminate the need 'code behind' and are often used with the MVVM pattern.

Try this one and see if it works for you.

public class EventFocusAttachment
{
    public static Control GetElementToFocus(Button button)
    {
        return (Control)button.GetValue(ElementToFocusProperty);
    }

    public static void SetElementToFocus(Button button, Control value)
    {
        button.SetValue(ElementToFocusProperty, value);
    }

    public static readonly DependencyProperty ElementToFocusProperty =
        DependencyProperty.RegisterAttached("ElementToFocus", typeof(Control), 
        typeof(EventFocusAttachment), new UIPropertyMetadata(null, ElementToFocusPropertyChanged));

    public static void ElementToFocusPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var button = sender as Button;
        if (button != null)
        {
            button.Click += (s, args) =>
                {
                    Control control = GetElementToFocus(button);
                    if (control != null)
                    {
                        control.Focus();
                    }
                };
        }
    }
}

And then in your XAML do something like...

<Button 
    Content="Click Me!" 
    local:EventFocusAttachment.ElementToFocus="{Binding ElementName=textBox}" 
    />
<TextBox x:Name="textBox" />

How to focus textbox on button click using wpf mvvm, Free source code and tutorials for Software developers and Focus . It will work, first of all, because you are asking to do it on button But in many cases you may need to solve more sophisticated problems of focusing, which is not a trivial WPF topic: Focusing something on button click sounds weird. WPF - Remove focus when clicking outside of a textbox. To avoid code behind you can use this Behavior The behavior WPF - Set Focus when a button is clicked


I'm not near visual studio so I can't actually try this right now, but off the top of my head, you should be able to do something like this:

FocusManager.FocusedElement="{Binding ElementName=txtName}">

Edit:

There is a followup question (asked more recently) about this here: How to set autofocus only in xaml? which contains this method, and a few different ideas on how to use it.

[Solved] Setting a Button to Focusable = false, Set the TabStop property to false . Both of these can be set in code. control (​on WPF, whole hierarchy of logical focus is supported, on WinForms Note: Click event will not fire as the control must take focus for the Click to  @Evk using a simple Button.Click event and setting myDataGrid.Focus() within Button.Click event in code-behind does not work. When I press up/down arrow key it does not move to next item in the datagrid, instead next control is getting the focus depending on if I click up or down arroy key.


You could also use a WPF Behavior...

    public class FocusElementAfterClickBehavior : Behavior<ButtonBase>
{
    private ButtonBase _AssociatedButton;

    protected override void OnAttached()
    {
        _AssociatedButton = AssociatedObject;

        _AssociatedButton.Click += AssociatedButtonClick;
    }

    protected override void OnDetaching()
    {
        _AssociatedButton.Click -= AssociatedButtonClick;
    }

    void AssociatedButtonClick(object sender, RoutedEventArgs e)
    {
        Keyboard.Focus(FocusElement);
    }

    public Control FocusElement
    {
        get { return (Control)GetValue(FocusElementProperty); }
        set { SetValue(FocusElementProperty, value); }
    }

    // Using a DependencyProperty as the backing store for FocusElement.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty FocusElementProperty =
        DependencyProperty.Register("FocusElement", typeof(Control), typeof(FocusElementAfterClickBehavior), new UIPropertyMetadata());
}

Here is the XAML to use the behavior.

Include namespaces:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 
xmlns:local="clr-namespace:WpfApplication1"

Attach WPF Behavior to button and bind element you want to set focus to:

<Button Content="Focus" Width="75">
    <i:Interaction.Behaviors>
        <local:FocusElementAfterClickBehavior FocusElement="{Binding ElementName=CheckBoxComboBox, Mode=OneWay}"/>
    </i:Interaction.Behaviors>
</Button>
<ComboBox x:Name="CheckBoxComboBox" HorizontalAlignment="Center" VerticalAlignment="Center" Width="120" Grid.Row="1"/>

So this way you have no code behind and it is reusable on any control that inherits from ButtonBase.

Hope this helps someone.

How to: Change the Color of an Element Using Focus Events, The following code behind creates the GotFocus and LostFocus event handlers. When the Button gains keyboard focus, the Background of the  In actual fact, WPF provides a much easier way of setting the initial focus by using the FocusManager. The FocusManager provides a set of static methods, properties, and events that you use to determine and set the focus scope [1] and to set the focused element within the focus scope.


you need a TriggerAction to invoke the Focus() method on the desired control.

public class SetFocusTrigger : TargetedTriggerAction<Control>
{
 protected override void Invoke(object parameter)
 {
    if (Target == null) return;

    Target.Focus();
 }
}

To have the focus set to a Control , you place a Triggers collection after your LayoutRoot (or any control really), select the event as the trigger, and select the SetFocusTrigger as the class to run. In the SetFocusTrigger declaration, you put the name of the control that you want to receive the focus by using the TargetName property.

<Button x:Name="LayoutRoot" >
<i:Interaction.Triggers>
    <i:EventTrigger EventName="Clicked">
        <local:SetFocusTrigger TargetName="StartHere"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

<TextBox x:Name="StartHere"/>
</Button>

FocusBehavior | WPF Controls, FocusBehavior allows you to set the focus to a UI control without utilizing code-​behind. XAML. <TextBox Text="This control is focused on button click:  Please note: The code above is simplified and just concerns setting the focus to a given control. As you would recall, I wanted the focus to be set on different control based on whether or not one of them contained text. But since it it trivial to adapt the code above for that, I have chosen to keep the eye on the ball. Finally


Is this what you want?

    <TextBox Name="txtName"></TextBox>
    <TextBox Grid.Row="1" Name="txtAddress"></TextBox>
    <Button Grid.Row="2" Content="Finish">
        <Button.Style>
            <Style TargetType="{x:Type Button}">
                <EventSetter Event="Click" Handler="MoveFocusOnClick" />
            </Style>
        </Button.Style>
        <!--<Button.Triggers>
            <EventTrigger RoutedEvent="Button.Click">
            </EventTrigger>
        </Button.Triggers>-->
    </Button>

c#:

    public void MoveFocusOnClick(object sender, RoutedEventArgs e)
    {
        Keyboard.Focus(txtName); // Or your own logic
    }

4. Code-Behind: Events and Handlers, What code do we want to run when the user clicks the button? hints that it is the C# code (the .cs part of the name tells us that) behind MainWindow.xaml. We named them txtWidth and txtHeight while we were setting properties in the The names are not used while we are designing the GUI, but they are used in the  A code-behind file implements an event handler method and then adds that method as a new event handler on the Button. The C# example uses the += operator to assign a handler to an event. This is the same operator that is used to assign a handler in the common language runtime (CLR) event handling model.


Creating a custom input dialog, For this particular dialog, I just wanted a Label telling the user which And here's the code for the dialog: that if the user clicks this button, the DialogResult of the Window should be set to false which To give focus to the TextBox upon showing the dialog, I've subscribed to the Is your preferred language not on the list? WPF-set Focus quand un bouton est cliqué - pas de Code derrière y a-t-il un moyen de passer Focus d'un contrôle à un autre en utilisant WPF Trigger s? comme dans l'exemple suivant:


Button Control In WPF, The Button class and XAML Button element represent a WPF Button control that is used to execute The following code adds the click event handler for a Button. Not let's get a little creative. The Background and Foreground properties of the Button set the background and foreground colors of a Button. If you use ToggleButton, you will be able to put it into the "Pressed" state easily by changing the "IsChecked" property. The only disadvantage is that you have to set the "IsChecked" property to false whenever the button is clicked (in the "Click" event handler), otherwise the button would stay pressed after the user clicks it.


MouseRightButtonDown Event, Click the 'Close' button to close the Popup to get information on another Graphic. The XAML code in this example is used in conjunction with the code-behind (C# or VB. Setting the ID attribute is key to accessing in the code-behind. Member variables) is not a good coding practice but since we need to control Properties  WPF-Remove focus when clicking outside of a textbox (7) I have some textboxes where I would like focus to behave a little differently than normal for a WPF application. Basically, I would like them to behave more like a textbox behaves on a webpage.