WPF - C# Desktop App - set focus, how?

Markus Freitag 3,786 Reputation points
2020-07-28T10:55:57.01+00:00

Hello,

How can I get the focus to move to the text field xy after an event?

How can I achieve that after an event the focus is automatically set on button A or button B?

In case of success, move on or in case of error MessageBox and stay in the text field.

Regards Markus

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,679 questions
0 comments No comments
{count} votes

3 additional answers

Sort by: Most helpful
  1. Peter Fleischer (former MVP) 19,231 Reputation points
    2020-07-28T13:27:43.37+00:00

    Hi Markus,
    for each UIElement con can set FocusManager.FocusedElement and Trigger to set focus to next UIElement like this:

            <DataTrigger Binding="{Binding ElementName=firstTextBox, Path=Text.Length}" Value="1">
                <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=secondTextBox}"/>
            </DataTrigger>
    

  2. Markus Freitag 3,786 Reputation points
    2020-07-28T13:52:17.987+00:00
       <TextBox Grid.Row="0" Grid.Column="1"   
                     Text="{Binding Path=ScannedMagazin, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"  
                     HorizontalAlignment="Left" Height="33" Margin="54,236,0,0"  TextWrapping="Wrap"  VerticalAlignment="Top" Width="621" FontSize="20" >  
                <TextBox.InputBindings>  
                    <KeyBinding Command="{Binding Cmd}"  CommandParameter="PressEnterScannedMagazine"  Key="Enter" />  
                </TextBox.InputBindings>  
            </TextBox>  
            <DataTrigger Binding="{Binding ElementName=firstTextBox, Path=Text.Length}" Value="1">  
                <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=secondTextBox}"/>  
            </DataTrigger>  
    

    Sorry it is not clear.
    firstTextBox is the name of the textbox?
    Value="1"

    Two possibilities.
    If the content of the textbox is good, select the button X.

    If the content of the text box is good, select the text box Y. Can you make a whole sample please?

    14095--decision.png


  3. Markus Freitag 3,786 Reputation points
    2020-07-29T05:38:24.223+00:00

    Hi,
    what is different between Name and x:Name?

       <TextBox Grid.Row="0" Grid.Column="0"  x:Name="txtNewOrder"  
                         Text="{Binding Path=NewOrderScan, Mode=TwoWay,  
       
    

    I need like a function for validate, not only the length.

    Works with length 6, but I need not the length.

    Input --- Check IsOK?, if OK goes to next textbox or set the focus for button XY.14140--use-wrong-way.png

    0 comments No comments