Search code examples
c#xamleventscursorfocus

Setting focus on a button in xaml and having a text box automatically have the type cursor in it


Hello I currently have a xaml form pop up with some text, a text box and button called confirm.

Is there a way I can have the form appear with the cursor already in the text box so that the user can start typing straight away and have focus on the button so that when they press enter, it runs the buttons on_Click handler.

my xaml code is as follows for the textbox and button:

<TextBox x:Name="SessionName"  Grid.Row="4" FontFamily="Calibri" FontSize="14"  IsTabStop="True" TabIndex="1" MaxLines="2" AcceptsTab="True" AcceptsReturn="False" BorderThickness="1" Height="30" Width="300" HorizontalAlignment="Center" Margin="0,5,10,5" ForceCursor="True" >
            <TextBox.ContextMenu>
                <ContextMenu/>
            </TextBox.ContextMenu>
        </TextBox>

<Button x:Name="startAppButton" Content="Start" Grid.Row="5" Height="25" Width="150" Click="StartAppButton_Click" HorizontalAlignment="Center" />

For my .cs file, the code is as follows:

public class Class
{
    public WelcomePage()
    {
        InitializeComponent();

        /*disables window modification.*/
        this.WindowStyle = WindowStyle.None;
    }

    public static string sessionName { set; get; }

    private void StartAppButton_Click(object sender, RoutedEventArgs e)
    {
         if (SessionName.Text.ToString().Equals(""))
         {
             System.Windows.MessageBox.Show("Please give your session a name", "Error",    
             MessageBoxButton.OK, MessageBoxImage.Error);
         }
         else
         {
             sessionName = SessionName.Text.ToString();
             Calibration.Degree_Choice dc = new Calibration.Degree_Choice();
             this.Hide();
             dc.ShowDialog();
             this.Close();
         }
    } 

}   

Any advice as to if this is possible would be greatly appreciated.

J


Solution

  • You cannot have the focus set to two controls at the same time, however you can mark the button as the "default button" for the form (by setting IsDefault), and it'll accept return regardless of the focus. There is also a way of specifying which control is focused at the start (FocusManager.FocusedElement).

    Try something like this:

    <Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="75.705" Width="277.037"
        FocusManager.FocusedElement="{Binding ElementName=textBox1}">
    <DockPanel>
        <Button IsDefault="True" Click="Button_Click" Content="OK" DockPanel.Dock="Right" Width="50"/>
        <TextBox Name="textBox1"/>        
    </DockPanel>