在 XAML 中将焦点设置在按钮上,并使文本框自动包含类型光标

本文关键字:文本 光标 类型 包含 XAML 焦点 设置 按钮 | 更新日期: 2023-09-27 18:35:43

您好,我目前弹出了一个带有一些文本的xaml表单,一个文本框和名为confirm的按钮。

有没有办法让我在光标已经在文本框中的情况下显示表单,以便用户可以立即开始键入并将焦点放在按钮上,以便在他们按 Enter 时,它会on_Click处理程序运行按钮。

我的 XAML 代码对于文本框和按钮如下所示:

<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" />

对于我的.cs文件,代码如下:

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();
         }
    } 
}   

关于这是否可能的任何建议将不胜感激。

J

在 XAML 中将焦点设置在按钮上,并使文本框自动包含类型光标

不能同时将焦点设置为两个控件,但是可以将按钮标记为窗体的"默认按钮"(通过设置 IsDefault ),并且无论焦点如何,它都将接受返回。还有一种方法可以指定哪个控件集中在开始时(FocusManager.FocusedElement)。

尝试这样的事情:

<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>